35
A
回答
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,但我可以用:-)
3
1
处理你的主申请表的Activated event。
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();
11
,因为它很可能是在UI的一些元素具有包含焦点的形式是积极的尝试:
this.ContainsFocus
http://msdn.microsoft.com/en-us/library/system.windows.forms.control.containsfocus(v=vs.110).aspx
+1
这只适用于如果你有一个表单(并没有对话框等)。 – Cameron
0
在WPF中最简单的方法来检查,如果一个窗口是活动的是:
if(this.IsActive)
{
//the window is active
}
1
我找到的解决方案,它既不需要本地调用,也不需要处理事件是检查Form.ActiveForm
。在我的测试中,当应用程序中没有窗口为焦点时为null
,否则为非空。
var windowInApplicationIsFocused = Form.ActiveForm != null;
啊,这是特定于winforms的。但这适用于我的情况;-)。
相关问题
- 1. 确定网页是否具有前景窗口焦点/活动选项卡?
- 2. 如何确定进程是否为当前活动/前台应用程序
- 3. Angular + bootstrap-ui,检查当前选项卡是否已经激活
- 4. Windows.Forms:激活已经在正确运行的应用程序FormWindowState
- 5. 当应用程序已经运行时激活GPS
- 6. 确定DataGrid是否具有基于ScrollViewer.ScrollChanged的焦点
- 7. 如何确定NSSearchField/NSTextField是否具有输入焦点?
- 8. 没有焦点/激活的表单
- 9. 激活Windows应用程序总是
- 10. qt应用程序激活
- 11. 应用程序激活
- 12. 是否可以通过bat脚本确定焦点窗口/应用程序?
- 13. 如何激活setInterval()使文本控件具有焦点
- 14. 如何检查我的应用程序是否有焦点?
- 15. 焦点当前程序/文件名(Windows)
- 16. 确定哪些元素具有焦点
- 17. 确定哪个控件具有焦点
- 18. 确定是否有键按下当前
- 19. 删除焦点从当前活动
- 20. 如何激活应用程序并将焦点集中在gtk/ubuntu上?
- 21. 如何确定应用程序是否是Web应用程序
- 22. 如果我的应用程序已具有焦点,如何检测新的Intent?
- 23. 如何检查哪个进程当前具有焦点
- 24. 如何确定当前的应用程序是否为中信任
- 25. 确定我的应用程序是否在前台
- 26. 如何以编程方式确定Android中当前活动的应用程序
- 27. VSTO:应用程序焦点
- 28. 如何找出哪个应用程序具有焦点
- 29. 当应用程序未运行时自动激活进程
- 30. 确定在点击通知时是否显示应用程序
你是说你的个人windowsform应用程序或任意? – Tigran
是这样的? http://stackoverflow.com/questions/2183541/c-detecting-which-application-has-focus – 2011-08-23 14:43:45
个人 - 因此“当前的应用程序”;-) – Cameron