Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/283.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C#-设置前景窗口并使其聚焦_C#_Wpf_Focus_Foreground - Fatal编程技术网

C#-设置前景窗口并使其聚焦

C#-设置前景窗口并使其聚焦,c#,wpf,focus,foreground,C#,Wpf,Focus,Foreground,我正在尝试创建一个WPF应用程序,该应用程序保持在后台,并在识别击键时开始工作。 我希望它大部分时间都被隐藏,当按下字母键时显示,当按下空格键时消失 我正在使用以下代码: void kbdManager_LetterPressed(object sender, KeyPressedEventArgs args) { IntPtr hwnd = (IntPtr)User.GetForegroundWindow(); // Logic.. this.Show();

我正在尝试创建一个WPF应用程序,该应用程序保持在后台,并在识别击键时开始工作。 我希望它大部分时间都被隐藏,当按下字母键时显示,当按下空格键时消失

我正在使用以下代码:

void kbdManager_LetterPressed(object sender, KeyPressedEventArgs args)
{
    IntPtr hwnd = (IntPtr)User.GetForegroundWindow();

    // Logic..

    this.Show();

    // These worked a few times but don't anymore..
    // User.SetForegroundWindow(hwnd);
    // User.SetFocus(hwnd);
    // User.SwitchToThisWindow(hwnd, true);
    // User.SetActiveWindow(hwnd);
}

void kbdManager_SpacePressed(object sender, KeyPressedEventArgs args)
{
    IntPtr hwnd = (IntPtr)User.GetForegroundWindow();

    this.Hide();

    // It seems this.Hide changes the focus?
    User.SetForegroundWindow(hwnd);
}

 [DllImport("user32")]
 public static extern int SetForegroundWindow(HWND hwnd);

 [DllImport("user32")]
 public static extern int GetForegroundWindow();
为了检查GetForegroundWindow()是否真的有效,我使用了user32.dll中的GetWindowText()方法,并且在大多数情况下它似乎工作正常

我的问题是焦点- 当弹出我的应用程序时,我希望它显示出来(并且在Topmost属性设置为True时保持可见),然后将焦点返回到我输入的窗口,但是我的应用程序获得了焦点

为了解决这个问题,我尝试使用SetForegroundWindow()、SwitchToThisWindow()、SetFocus()和SetActiveWindow()。他们似乎都不适合我。。焦点偶尔会回到主窗口,但并不总是如此。我甚至尝试过不同的组合,但仍然不能始终如一地发挥作用

我认为这可能与我使用下载的键盘侦听器类来处理击键有关,因为调试器总是将我带到那里——即使我在上面显示的方法中有断点


有人能帮忙吗?

您的SpacePressed事件处理程序无法按预期工作,它会将前景设置为已具有前景的窗口。它应该做的是完全没有用的。将hwnd变量从LetterPressed事件处理程序中移出,现在您拥有了在调用Show()之前位于前台的窗口句柄。我想的是-如果我在LetterPressed中尝试执行的操作成功,那么我键入的窗口将位于前台,因此这可以工作。如果我将指针移出处理程序,我将永远不知道前景中到底是什么。我不知道如何捕捉焦点窗口已改变的事件。