C# 如何像在关闭事件中一样从wpf窗口移除焦点?

C# 如何像在关闭事件中一样从wpf窗口移除焦点?,c#,wpf,focus,C#,Wpf,Focus,我想从我的wpf窗口中移除焦点,并将焦点设置回最后一个“窗口”,就像关闭正常wpf窗口时发生的那样 我的WPF窗口的工作原理类似于普通“Windows窗口”上的一层。我只是不想每次单击“图层WPF窗口”上的某个内容时都失去焦点 我的解决方法是使用Button\u Click事件方法将焦点设置回最后一个“Windows窗口” 希望你能帮助我,因为我在互联网上找不到关于这个不寻常问题的任何信息。你能做的就是最小化窗口。 这将使“最后一个窗口”成为焦点 你需要用p/Invoke把你的手弄脏。我们需要W

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

我的WPF窗口的工作原理类似于普通“Windows窗口”上的一层。我只是不想每次单击“图层WPF窗口”上的某个内容时都失去焦点

我的解决方法是使用Button\u 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);
}

这是由操作系统处理的,而不是WPF。我认为如果不关闭窗口,或者不借助WinAPIsI添加更多信息,就无法做到这一点。也许我的问题有一个解决办法。谢谢你的回答,但我只想把焦点放回去,让窗口打开。我想你有一个打字错误。我想您需要
hNext=GetWindow(hNext,GW\uhwndnext)@Joulukuusi它工作得很好,对我帮助很大。问题是,当我的WPF窗口设置为最顶层时(我希望它用作一个层),它不起作用。我尝试了
切换到此窗口(IntPtr hWnd,bool fAltTab)
方法,我也遇到了同样的问题。当“我的窗口”不是最上面的窗口时,该功能可以工作。@AntiStoopMode,您不应该使用
切换到此窗口
,因为
此功能不适用于一般用途。在Windows的后续版本中,它可能会被更改或不可用(引用自)。一种可能的解决方法是在
按钮的开头设置
TopMost=false
,然后在
窗口中将其还原为
true
。GotFocus
事件。@Joulukuusi非常感谢!通过设置
TopMost=false
并在稍后再次激活它,它可以按照我想要的方式工作。
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);
}