c# - 如何像在关闭事件中那样从 wpf 窗口中删除焦点?

标签 c# wpf focus

我想从我的 wpf 窗口中移除焦点并将焦点设置回最后一个“windows 窗口”,就像我关闭普通 wpf 窗口时发生的那样。

我的 WPF 窗口就像普通“Windows 窗口”上的一层一样。我只是不想每次在“图层 WPF Windows”上单击某些内容时都失去焦点。

我的解决方法是使用 Button_Click 事件方法将焦点设置回最后一个“Windows 窗口”。

希望你能帮助我,因为我在互联网上找不到关于这个不常见问题的任何信息。

最佳答案

您需要亲自动手使用 P/Invoke。我们需要 WinAPI 中的这些函数:

[DllImport("user32.dll")]
static extern IntPtr GetWindow(IntPtr hWnd, uint wCmd);
const uint GW_HWNDNEXT = 2;

[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool SetForegroundWindow(IntPtr hWnd);

[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool IsWindowVisible(IntPtr hWnd);

如何使用它们:

private void Button_Click(object sender, RoutedEventArgs e)
{
    // Get the WPF window handle
    IntPtr hWnd = new WindowInteropHelper(Application.Current.MainWindow).Handle;

    // Look for next visible window in Z order
    IntPtr hNext = hWnd;
    do
        hNext = GetWindow(hNext, GW_HWNDNEXT);
    while (!IsWindowVisible(hNext));

    // Bring the window to foreground
    SetForegroundWindow(hNext);
}

关于c# - 如何像在关闭事件中那样从 wpf 窗口中删除焦点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13384191/

相关文章:

c# - 将 WCF 与遗留复杂类型一起使用

WPF 绑定(bind) - StringFormat - 不格式化

javascript - 表单输入在 IE 中失去对滚动条单击的关注

android - 在 RecyclerView 中获取 EditText 的焦点

c# - 如何限制 asp.net 中 XML 记录中显示的字符数?

c# - C# 5 中的新异步/等待功能如何与消息循环集成?

c# - uwp:如何在 x:DataType 之外的 DataTemplate 内绑定(bind)数据?

c# - 关于构建操作的澄清

c# - WPF:如何在具有不同名称的 for 循环内创建 UserControl 的多个实例?

css 悬停在图片上