WPF - 防止在单击鼠标时激活窗口

本文关键字:鼠标 激活 窗口 单击 WPF | 更新日期: 2023-09-27 18:34:26

我正在编写屏幕键盘,因为在旧机器上打开/关闭内置屏幕键盘很慢。

当我单击按钮时,我想保持主窗口的焦点并防止键盘窗口获得焦点。类似于屏幕键盘上的内置Windows 10。

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

此代码没有区别,单击鼠标时仍会激活键盘窗口。

WPF - 防止在单击鼠标时激活窗口

如果我在窗口创建时设置它,它对我有用:

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