Mayday Malone
Mayday Malone

Reputation: 1

InputSimulator sends Key to wrong Process after Re-Activating WPF Window

The Problem:

I have an active WPF Window. On Creation a process is set as the owner of the Window. Now when the Key-Down event is fired on the WPF window the Key should be passed to the main Process.

At first i set the Focus to main process using SetForegroundWindow(). The the key is send using InputSimulator.

So far this works as expected. However, after sending the Key, the Wpf Window should get back to focus, so it can catch the next key presses.

I'm trying to call Activate() on the WPF Window. The problem that now occurs is that Key send by the InputSimulator is no longer passed to the main process, but instead is caught by the WPF Window.

Code

Heres the code:

This is the creation of the Window

public void createWindow() 
{
    CommandLineWindow win = new CommandLineWindow();
    helper = new WindowInteropHelper(win);
    Process oCurrent = Process.GetCurrentProcess();
    var ww = new WindowWrapper(oCurrent.MainWindowHandle); 
    helper.Owner = oCurrent.MainWindowHandle;
    win.ShowDialog();
}
 

The implementation of the WindowWrapper:

public class WindowWrapper : System.Windows.Forms.IWin32Window
{
    public WindowWrapper(IntPtr handle)
    {
        _hwnd = handle;
    }
    public IntPtr Handle
    {
        get { return _hwnd; }
    }
    private IntPtr _hwnd;
}           

And my Window.KeyDown Handler:

private void Window_KeyDown(object sender, KeyEventArgs e)
{
    if (e.Key == Key.X)
    {
         //Do something                 
         SetForegroundWindow(helper.Owner);
         new InputSimulator().Keyboard.KeyDown(WindowsInput.Native.VirtualKeyCode.VK_Y);
         this.Activate();
    }
}

Upvotes: 0

Views: 327

Answers (0)

Related Questions