【问题标题】:WPF- Prevent window from being activated on mouse clickWPF-防止在鼠标单击时激活窗口
【发布时间】:2016-02-13 23:20:08
【问题描述】:

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

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

这段代码没有区别,鼠标点击时键盘窗口仍然被激活。

【问题讨论】:

  • Application.Current.MainWindow = this; 放入YourMainWindow Loaded 事件中,将Activate((YourMainWindow )Application.Current.MainWindow)); 放入键盘窗口MouseUp 事件中。
  • 我尝试了窗口 PreviewMouseLeftButtonDown 但在鼠标单击之前调用了 OnActivated,因此主窗口失去了清除 Keyboard.FocusedElement 的框架的焦点。

标签: c# wpf


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-08
    • 1970-01-01
    • 1970-01-01
    • 2020-01-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多