【问题标题】:How to remove focus from wpf window like in close event?如何在关闭事件中从 wpf 窗口中移除焦点?
【发布时间】:2012-11-15 05:05:54
【问题描述】:

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

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

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

希望您能帮助我,因为我无法在互联网上找到有关此不常见问题的任何信息。

【问题讨论】:

  • 由操作系统处理,而不是 WPF。我认为如果不关闭窗口或诉诸 WinAPI 就无法做到这一点
  • 我添加了更多信息。也许我的问题有解决方法。

标签: c# wpf focus


【解决方案1】:

您需要亲身体验 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);
}

【讨论】:

  • 我认为你有一个错字。我想你想要hNext = GetWindow(hNext, GW_HWNDNEXT);
  • @Joulukuusi 它工作正常,对我有很大帮助。问题是当我的 WPF 窗口设置为 TopMost 时它不起作用(因为我希望它用作图层)。我尝试了SwitchToThisWindow(IntPtr hWnd, bool fAltTab) 方法,我也遇到了同样的问题。当我的窗口不是 TopMost 时它可以工作。
  • @AntiStoopMode,你不应该使用SwitchToThisWindow,因为This function is not intended for general use. It may be altered or unavailable in subsequent versions of Windows(引用自msdn.microsoft.com/en-us/library/windows/desktop/ms633553.aspx)。一种可能的解决方法是在Button_Click 的开头设置TopMost = false,并在Window.GotFocus 事件中将其恢复为true
  • @Joulukuusi 非常感谢!通过设置TopMost = false 并稍后再次激活它,它可以按照我想要的方式工作。
【解决方案2】:

您可以做的是最小化窗口。 这会将焦点放在“最后一个窗口”上。

window.WindowState = System.Windows.WindowState.Minimized;

【讨论】:

  • 感谢您的回答,但我只想将焦点返回并让窗口打开。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多