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

时间:2016-02-13 23:20:09

标签: c# wpf

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

当我点击一个按钮时,我想让主窗口保持对焦并防止键盘窗口获得焦点。类似于内置的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);

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

1 个答案:

答案 0 :(得分:0)

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

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