我正在寻找创建一个C#应用程序,根据当前具有焦点的应用程序来更改内容.因此,如果用户使用的是Firefox,我的应用就会知道.适用于Chrome,Visual Studio,TweetDeck等.
这是可能的,如果是这样的话 - 我将如何实现它?
我有一种感觉,我要求的很多 - 但值得一试.
提前谢谢了.
这可以使用作为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);
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
看看Application.AddMessageFilter,并查找WM_ACTIVATEAPP消息,它会告诉您应用程序何时被激活,即获得焦点.
咕噜噜。像往常一样,在发布这个问题之前,我花了一些时间谷歌搜索。
一旦我最终发布了这个问题,我的下一次谷歌搜索就揭示了答案。
我还没有测试它,但它看起来好像GetForegroundWindow()是关键。
我没有重写已经写的内容,而是提供信息的页面链接:
http://www.csharphelp.com/2006/08/get-current-window-handle-and-caption-with-windows-api-in-c/
为任何人的时间道歉,我通过询问 Googalable (?) 答案而浪费了。