2011-08-23 95 views

回答

61

这工作:

/// <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,但我可以用:-)

+0

这可能与'子窗口一起工作,但它并没有区分他们和他们的父母。 – Chris

+2

@Chris:是的,就是这一点。子窗口仍然是应用程序的一部分。我想通过'目前的应用程序'我真的是'现在的过程'。 – Cameron

0

首先得到使用的句柄:

IntPtr myWindowHandle;

myWindowHandle = new WindowInteropHelper(Application.Current.MainWindow).Handle; 

HwndSource source = (HwndSource)HwndSource.FromVisual(this); 
myWindowHandle = source.Handle; 

然后比较whethers它是ForeGroundWindow:

if (myWindowHandle == GetForegroundWindow()) 
{ 
    // Do stuff! 

} 

[DllImport("user32.dll")] 
private static extern IntPtr GetForegroundWindow(); 
+0

如果子窗口是前景窗口,该怎么办?应用程序仍然有重点,但不是主窗口。 – Cameron

+0

@cameron,真的,但你想到了很多,对downvote太伤心了:-)这批评也不适用于其他建议的答案吗? – Cilvic

+0

我没有对任何人投降或投票,但只要主窗口是所有其他人的父母(或祖父母),“激活”答案就会工作。 – Cameron

0

在WPF中最简单的方法来检查,如果一个窗口是活动的是:

if(this.IsActive) 
{ 
//the window is active 
} 
1

我找到的解决方案,它既不需要本地调用,也不需要处理事件是检查Form.ActiveForm。在我的测试中,当应用程序中没有窗口为焦点时为null,否则为非空。

var windowInApplicationIsFocused = Form.ActiveForm != null; 

啊,这是特定于winforms的。但这适用于我的情况;-)。

相关问题