确定是否计划在.NET中的活动窗口 [英] Determine Whether Program is the Active Window in .NET
问题描述
我有一个C#/。NET应用程序,我想实现以下行为:
I have a C#/.NET app and I want to implement the following behavior:
我有一个弹出式菜单。每当在用户点击任何东西的 的是没有的弹出式菜单,我想在弹出菜单中关闭该应用程序。
I have a popup menu. Whenever the user clicks on anything within the application that is not the popup menu, I want the popup menu to close.
不过,只要用户不在应用程序,我不希望任何事情发生。
However, whenever a user is not in the application I don't want anything to happen.
我想通过LostFocus事件来管理这一点,但我无法确定我的应用程序是否是活动窗口。在code看起来是这样的。
I'm trying to manage this through the LostFocus event, but I'm having trouble determining whether my application is the active window. The code looks something like this.
private void Button_LostFocus(object sender, System.EventArgs e)
{
if (InActiveWindow()) {
CloseMenu()
}
else {
// not in active window, do nothing
}
}
我需要知道的是如何实现的InActiveWindow()方法。
What I need to know is how to implement the InActiveWindow() method.
推荐答案
您可以P /调用到的 GetForegroundWindow()和比较HWND返回给应用程序的form.Handle属性。
You could P/Invoke into GetForegroundWindow(), and compare the HWND returned to the application's form.Handle property.
一旦你的把柄,你也可以的P / Invoke的 GetAncestor(),以获取根所有者窗口。这应该是您的应用程序的主,启动窗口的句柄,如果这是你的应用程序。
Once you have the handle, you can also P/Invoke GetAncestor() to get the root owner window. This should be the handle of your application's main, startup window, if this is in your application.
这篇关于确定是否计划在.NET中的活动窗口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!