确定当前应用程序是否已激活(具有焦点)
本文关键字:焦点 激活 应用程序 是否 | 更新日期: 2023-09-27 18:06:30
注意:有一个非常相似的问题,但它是WPF特有的;这个不是。
如何确定当前应用程序是否已激活(即具有焦点(?
这是有效的:
/// <summary>Returns true if the current application has focus, false otherwise</summary>
public static bool ApplicationIsActivated()
{
var activatedHandle = GetForegroundWindow();
if (activatedHandle == IntPtr.Zero) {
return false; // No window is currently activated
}
var procId = Process.GetCurrentProcess().Id;
int activeProcId;
GetWindowThreadProcessId(activatedHandle, out activeProcId);
return activeProcId == procId;
}
[DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
private static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern int GetWindowThreadProcessId(IntPtr handle, out int processId);
它的优点是线程安全,不需要主窗体(或其句柄(,并且不特定于WPF或WinForms。它将适用于子窗口(甚至是在单独线程上创建的独立窗口(。此外,不需要任何设置。
缺点是它使用了一点p/Invoke,但我可以接受:-(
我发现的既不需要本机调用也不需要处理事件的解决方案是检查Form.ActiveForm
。在我的测试中,这是null
,当时应用程序中没有窗口被聚焦,否则就是非空的。
var windowInApplicationIsFocused = Form.ActiveForm != null;
啊,这是winforms特有的。但这适用于我的情况;-(。
因为UI中的某些元素可能包含要激活的表单的焦点,请尝试:
this.ContainsFocus
http://msdn.microsoft.com/en-us/library/system.windows.forms.control.containsfocus(v=vs.110(.aspx
您可以订阅主窗口的激活事件
首先使用:获取句柄
IntPtr myWindowHandle;
myWindowHandle = new WindowInteropHelper(Application.Current.MainWindow).Handle;
或
HwndSource source = (HwndSource)HwndSource.FromVisual(this);
myWindowHandle = source.Handle;
然后比较一下它是否是前景窗口:
if (myWindowHandle == GetForegroundWindow())
{
// Do stuff!
}
[DllImport("user32.dll")]
private static extern IntPtr GetForegroundWindow();
处理主应用程序窗体的Activated事件。
在WPF中,检查窗口是否处于活动状态的最简单方法是:
if(this.IsActive)
{
//the window is active
}