5

I am writing an on screen keyboard since opening/closing inbuilt on screen keyboard is slow on older machines.

When I click on a button, I want to keep the main window in focus and prevent keyboard window from gaining focus. Similar to the inbuilt Windows 10 on screen keyboard.

https://stackoverflow.com/a/12628353/4077230

protected override void OnActivated(EventArgs e)
{
    base.OnActivated(e);

    //Set the window style to noactivate.
    WindowInteropHelper helper = new WindowInteropHelper(this);
    SetWindowLong(helper.Handle, GWL_EXSTYLE,
        GetWindowLong(helper.Handle, GWL_EXSTYLE) | WS_EX_NOACTIVATE);
}   

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

[DllImport("user32.dll")]
public static extern IntPtr SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong);

[DllImport("user32.dll")]
public static extern int GetWindowLong(IntPtr hWnd, int nIndex);

This code makes no difference, keyboard window is still activated on mouse click.

Community
  • 1
  • 1
gamedevranjit
  • 91
  • 1
  • 8
  • put `Application.Current.MainWindow = this;` in YourMainWindow Loaded event and `Activate((YourMainWindow )Application.Current.MainWindow));` in keyboard window MouseUp event . – Maria Feb 14 '16 at 10:46
  • I tried window PreviewMouseLeftButtonDown but OnActivated is called before the mouse click so the main window loses focus for a frame which clears the Keyboard.FocusedElement. – gamedevranjit Feb 14 '16 at 21:07
  • 1
    Have you tried https://stackoverflow.com/a/4037358? – jnm2 Aug 05 '17 at 22:57

1 Answers1

0

Works for me if I set it at window creation time:

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);

protected override void OnSourceInitialized(EventArgs e)
{
  var hWnd = new WindowInteropHelper(this).Handle;
  int style = GetWindowLong(hWnd, GWL_EXSTYLE);
  SetWindowLong(hWnd, GWL_EXSTYLE, style | WS_EX_NOACTIVATE);

  base.OnSourceInitialized(e);
}
GazTheDestroyer
  • 20,722
  • 9
  • 70
  • 103