2010-02-02 58 views
16

我正在创建一个C#应用程序,根据哪个应用程序当前有焦点来更改内容。所以如果用户使用Firefox,我的应用程序会知道这一点。同样适用于Chrome,Visual Studio,TweetDeck等。C#:检测哪个应用程序有焦点

这是否可能,如果是这样 - 我将如何去实现它?

我有一种感觉,我要求很多 - 但它值得一试。

非常感谢提前。

+0

使用辅助功能接口。这正是他们所要做的。 – 2012-02-08 11:18:21

+0

这个问题的接受答案扩展了@ RaymondChen的评论:http://stackoverflow.com/questions/11711400/how-to-monitor-focus-changes – John 2014-02-19 17:15:46

回答

7

看看Application.AddMessageFilter,查找WM_ACTIVATEAPP消息,它会告诉你应用何时被激活,即接收焦点。

+6

'Application.AddMessageFilter'只拦截当前进程的消息,而不是其他进程。 – larsmoa 2014-09-16 19:07:40

4

Grrr。就像往常一样,我在发布这个问题之前花了一些时间Google搜索。

我终于发布了这个问题后,我的下一个Google搜索就显示了答案。

我还没有测试它,但它看起来好像GetForegroundWindow()是关键。

,而不是我重写什么已经写了,下面是提供的信息的网页的链接:

http://www.csharphelp.com/2006/08/get-current-window-handle-and-caption-with-windows-api-in-c/

Appologies对任何人的时间通过询问Googalable答案我已经浪费了(?)。

+1

AddMessageFilter的优点是纯粹的托管代码,GetForegroundWindows不那么“沉重“(您需要时检查前台窗口,而不是通知每个应用程序更改),但需要PInvoke。您现在只需要选择;) – munissor 2010-02-02 11:31:02

7

这可以使用属于WPF的Automation framework在纯.NET中完成。添加引用UIAutomationClientUIAutomationTypes和使用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); 
      } 
     } 
    } 
} 
相关问题