确定当前应用程序是否已激活(具有焦点)

Cam*_*ron 45 .net c#

注意:有一个非常相似的问题,但它是WPF特有的; 这个不是.

如何确定当前应用程序是否已激活(即具有焦点)?

Cam*_*ron 71

这有效:

/// <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);
Run Code Online (Sandbox Code Playgroud)

它具有线程安全的优点,不需要主窗体(或其句柄),也不是特定于WPF或WinForms.它将适用于子窗口(甚至是在单独的线程上创建的独立窗口).此外,还需要零设置.

缺点是它使用了一点P/Invoke,但我可以忍受:-)

  • @Chris:是的,这就是重点.子窗口仍然是应用程序的一部分.我想通过'当前应用'我的意思是'当前的过程'. (4认同)

小智 11

因为您的UI中的某些元素可能包含要激活的表单的焦点,请尝试:

this.ContainsFocus
Run Code Online (Sandbox Code Playgroud)

http://msdn.microsoft.com/en-us/library/system.windows.forms.control.containsfocus(v=vs.110).aspx

  • 这仅适用于您有一个表单(并且没有对话框等). (2认同)

bin*_*nki 7

我发现既不需要本机调用也不需要处理事件的解决方案是检查Form.ActiveForm. 在我的测试中,那是null应用程序中没有窗口被聚焦并且否则非空的时候。

var windowInApplicationIsFocused = Form.ActiveForm != null;
Run Code Online (Sandbox Code Playgroud)

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