C#:检测哪个应用程序具有焦点

标签 c#

我想创建一个 C# 应用程序,它根据当前具有焦点的应用程序更改内容。因此,如果用户使用的是 Firefox,我的应用程序就会知道这一点。同样适用于 Chrome、Visual Studio、TweetDeck 等。

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

我觉得我的要求太多了 - 但值得一试。

非常感谢。

最佳答案

这可以在纯 .NET 中使用 Automation framework 完成这是 WPF 的一部分。添加对 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);
            }
        }
    }
}

关于C#:检测哪个应用程序具有焦点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2183541/

相关文章:

c# - 使用 XmlSerializer 序列化到特定的 XSD

c# - 在 C# 中概括和聚合 XML 转储的最佳方法是什么?

c# - 将 linq to sql 结果放入层次结构中,以便在无序列表中使用(对于 jquery 树)

c# - 抽象方法是虚拟的吗?

c# - Parallel.Foreach 中的 Ninject 异常

c# - 类库中的 .net Reference Web

c# - 如何在前瞻中匹配字符串的结尾?

c# - 可以将 C# 扩展方法添加到 F# 类型吗?

c# - c#中的64位应用程序中的32位dll

c# - 泛型方法中的隐式类型转换