C#:检测哪个应用程序具有焦点
我正在寻找创建一个C#应用程序,根据当前具有焦点的应用程序来更改内容。 因此,如果用户使用Firefox,我的应用程序就会知道。 适用于Chrome,Visual Studio,TweetDeck等。
这是可能的,如果是这样的话 – 我将如何实现它?
我有一种感觉,我要求很多 – 但值得一试。
提前谢谢了。
看看Application.AddMessageFilter
,并查找WM_ACTIVATEAPP消息,它会告诉您应用程序何时被激活,即获得焦点。
这可以使用作为WPF一部分的Automation框架在纯.NET中完成。 添加对UIAutomationClient
和UIAutomationTypes
引用,并使用Automation.AddAutomationFocusChangedEventHandler
,例如:
public class FocusMonitor { public FocusMonitor() { AutomationFocusChangedEventHandler focusHandler = OnFocusChanged; Automation.AddAutomationFocusChangedEventHandler(focusHandler); } private void OnFocusChanged(object sender, AutomationFocusChangedEventArgs e) { AutomationElement focusedElement = sender as AutomationElement; if (focusedElement != null) { int processId = focusedElement.Current.ProcessId; using (Process process = Process.GetProcessById(processId)) { Debug.WriteLine(process.ProcessName); } } } }
哎呀。 通常情况下,我在发布此问题之前花了一些时间谷歌搜索。
一旦我最终发布了这个问题,我的下一个Google搜索就会显示答案。
我还没有测试它,但看起来好像GetForegroundWindow()
是关键。
而不是我重写已经写的内容,这里是提供信息的页面的链接:
http://www.csharphelp.com/2006/08/get-current-window-handle-and-caption-with-windows-api-in-c/
对于任何人的时间而言,我都会通过询问可笑的(?)答案而浪费时间。