Multiple windows focus issues.

Mar 5, 2010 at 9:54 AM

Given the following situation:

- WPF main window application
- class library that interacts with a USB device or which spawns a new window.

The class library is basically a software simulator for an external USB device which contains a few buttons, namely ENTER, CANCEL, LEFT and RIGHT.

In my main window I have an update loop which listens to the class library.

ClassLibrary.AbstractDevice.Update();
if (ClassLibrary.AbstractDevice.HasKeyBeenPressed) {
    InputSimulator.SimulateKeyDown(VirtualKeyCode.RETURN);
}

In debug mode the class library shows the simulator. This is a new WPF window. When I press the ENTER button on my simulator window the HasKeyBeenPressed is correctly detected and the SimulateKeyDown function is called. However, that's where it stops. It doesn't perform the action the ENTER press should do. When I directly press the ENTER key on my keyboard, or I call the SimulateKeyDown function in the update loop of my main application it works. My guess is that because the simulator window has focus the key presses are not detected in my main application. Would there be a way to specify to which window has to handle the key press event?

Regards

Mar 5, 2010 at 10:31 AM

I think I might have found a solution.

From within my simulator window I can call Application.Current.Windows[0].Focus(). The focus changes before the keypress event is handled so it executes my command.

Coordinator
Mar 8, 2010 at 12:01 AM

Hi,

Sorry I didn't get back to you earlier.  I'm glad you found the solution on your own.  A restriction of the SendInput API is that it only works on the currently focused window - I don't know of a way to target a particular window programmatically except to ensure it actually has input focus.

The only other suggestion I had was to try SimulateKeyPress which simulates a KeyDown + KeyUp combination.  In some situations the combination is required to get the intended result.

Kind Regards,
Mike