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,但我可以忍受:-)
小智 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
我发现既不需要本机调用也不需要处理事件的解决方案是检查Form.ActiveForm. 在我的测试中,那是null应用程序中没有窗口被聚焦并且否则非空的时候。
var windowInApplicationIsFocused = Form.ActiveForm != null;
Run Code Online (Sandbox Code Playgroud)
啊,这是winforms特有的。但这适用于我的情况;-)。