C # How to change window focus onMouseEnter

I have a WPF application that I would like to become the current focused window whenever the mouse cursor moves over it. I currently have an onMouseEnter event that changes the cursor when the mouse moves over it, so I know the system will recognize that, however, I actually want the application itself to focus as if the used one clicked on him - so that I can then perform other operations. At the moment, if I move over it, the cursor changes, but if another application, like notepad, has focus, the focus will return to it after.

In the onMouseEnter handler, I tried "this.Focus ()" and "this.Activate ()", but neither achieved the same result as if I clicked on the application.

Any ideas?

+1


a source to share


3 answers


Edit: The posted answer won't work for WPF. Unfortunately.



Try this instead of WPF: http://blogs.msdn.com/nickkramer/archive/2006/03/18/554235.aspx

0


a source


WPF C # example with MouseEnter event connected to a grid control. If another application window has focus, it will remove it and give focus to the main window, as if the user had clicked on it.



    private void GrdContent_MouseEnter(object sender, MouseEventArgs e)
    {
        Application.Current.MainWindow.Activate();
    }

      

+1


a source


In WPF, just add this line to the MainWindow constructor to get the expected result.

MouseEnter += (s, e) => Activate();

      

This original one line answer will only work if you are not interacting with any other window. The following will work even in this case, but you need the "AutoItX.Dotnet" Nuget package.

private IntPtr myHandle;
public MainWindow() {
  myHandle =  new System.Windows.Interop.WindowInteropHelper(this).Handle;
  MouseEnter += (s, e) => {
    Activate();
    if (AutoIt.AutoItX.WinActive(myHandle) == 0)
      AutoIt.AutoItX.WinActivate(myHandle);
    };

      

0


a source