11

The onscreen keyboard in Windows 7 will let you keep focus on a textbox while you type using the keyboard. In C# and .Net, how can I force another application to retain focus while accepting input just like the Win7 onscreen keyboard? Or perhaps a better way to word it, how can I not have my app take focus when interacted with?

I have tried LockSetForegroundWindow and have seen no results with it.

0

1 Answer 1

19

You have to set the WS_EX_NOACTIVATE extended style on your window. The easiest way is by using P/Invoke.

private const int WS_EX_NOACTIVATE = 0x08000000;
private const int GWL_EXSTYLE = -20;

[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern int GetWindowLong(IntPtr hwnd, int index);

[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern int SetWindowLong(IntPtr hwnd, int index, int newStyle);

...

var window = new Window();
window.SourceInitialized += (s, e) => {
    var interopHelper = new WindowInteropHelper(window);
    int exStyle = GetWindowLong(interopHelper.Handle, GWL_EXSTYLE);
    SetWindowLong(interopHelper.Handle, GWL_EXSTYLE, exStyle | WS_EX_NOACTIVATE);
};
window.Show();

You can also use WPF interop class HwndSource to create your window. Its constructor accepts the extended window style.

3
  • I'm at work right now and can't try this, but I'm very excited about a simple solution like this. When I get home, I'll throw this in and report back how it goes. Commented Jul 26, 2011 at 14:44
  • 1
    Just note that if window will have relation parent\owner with any other window than this flag WS_EX_NOACTIVATE will be ignored.
    – Ievgen
    Commented Feb 26, 2016 at 14:21
  • I notice if one tries to move the windows 7 online keyboard then when dragged, you get a border that moves as you move your mouse, just like with moving any other window. But if you set it to not activate ever, then do you find you lose that behaviour? Is there a way to maintain that behaviour but still have it not take focus when a button on it is clicked?
    – barlop
    Commented Nov 21, 2017 at 23:50

Not the answer you're looking for? Browse other questions tagged or ask your own question.