2011-08-23 93 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的。但這適用於我的情況;-)。

相關問題