battmanz
battmanz

Reputation: 2296

Force Window to have Focus When Opened

I have a WPF application that communicates with a C++ MFC application over a socket connection. If a user presses a particular button in the C++ application then a new WPF window is shown.

Here is the code that gets called to launch the WPF window:

var window = new Window();
window.Topmost = true;
window.Show();
window.Activate();
window.Topmost = false;

On certain machines, the first window (and only the first window) that is shown in this manner won't have keyboard focus. It will be in front of the C++ app, but the C++ app will still have keyboard focus. Is there something else I can do to force the WPF window to take keyboard focus every time?

Upvotes: 3

Views: 7650

Answers (3)

battmanz
battmanz

Reputation: 2296

It turns out that window.Activate() was returning false. Looking at that method's documentation, it says,

The rules that determine whether the window is activated are the same as those used by the Win32 SetForegroundWindow function (User32.dll).

The documentation for the SetForegroundWindow, then states:

A process that can set the foreground window can enable another process to set the foreground window by calling the AllowSetForegroundWindow function.

So the solution was to have the C++ app use the AllowSetForegroundWindow function to give the WPF app permission to set the foreground window.

Upvotes: 2

Lukas Kubis
Lukas Kubis

Reputation: 929

Try this:

var window = new Window();    
window.Show();
window.Activate();
window.Focus();
window.Topmost = true;
window.Topmost = false;

Upvotes: 4

jhontarrede
jhontarrede

Reputation: 124

Have you tried the Property Focusable on the Window to set to true and then in to call the window.Focus() ?

Upvotes: 2

Related Questions