如何监控焦点变化? [英] How to monitor focus changes?

查看:44
本文介绍了如何监控焦点变化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧,有时我正在打字,但很少发生某些事情会引起焦点的情况,我阅读了一些解决方案(甚至是 VB 手表),但它们不适用于我.是否有任何窗口范围的句柄"来处理任何焦点更改?

Well Sometimes I am typing and very rarely it happens that something steals focus, I read some solution (even a VB watch) but they don't apply to me. Is there any windows-wide 'handle' which handles ANY focus changes?

使用哪种语言无关紧要,C、C++、VB.NET、C#、任何与 .NET 或 Windows 相关的东西、Batch、PoweShell、VBS 脚本……只要我能够监视每个焦点变化和将其登录到文件/cmd 窗口/可视窗口中.

It doesn't matter in which language, C, C++, VB.NET, C#, Anything .NET or windows related, Batch, PoweShell, VBS Script... As Long as I am able to monitor every focus change and log it into a file/cmd window/visual window.

类似于:

   void event_OnWindowsFocusChange(int OldProcID, int NewProcID);

会非常有用.或者也许已经有工具可以做到这一点(我找不到?)

would be very usefull. Or maybe there are tools for this already (which I can't find?)

推荐答案

一种方法是使用 Windows UI 自动化 API.它公开了一个全局焦点改变事件.这是我想出的一个快速示例(在 C# 中).注意,您需要添加对 UIAutomationClient 和 UIAutomationTypes 的引用.

One way would be to use the windows UI Automation API. It exposes a global focus changed event. Here is a quick sample I came up with (in C#). Note, you need to add references to UIAutomationClient and UIAutomationTypes.

using System.Windows.Automation;
using System.Diagnostics;

namespace FocusChanged
{
    class Program
    {
        static void Main(string[] args)
        {
            Automation.AddAutomationFocusChangedEventHandler(OnFocusChangedHandler);
            Console.WriteLine("Monitoring... Hit enter to end.");
            Console.ReadLine();
        }

        private static void OnFocusChangedHandler(object src, AutomationFocusChangedEventArgs args)
        {
            Console.WriteLine("Focus changed!");
            AutomationElement element = src as AutomationElement;
            if (element != null)
            {
                string name = element.Current.Name;
                string id = element.Current.AutomationId;
                int processId = element.Current.ProcessId;
                using (Process process = Process.GetProcessById(processId))
                {
                    Console.WriteLine("  Name: {0}, Id: {1}, Process: {2}", name, id, process.ProcessName);
                }
            }
        }
    }
}

这篇关于如何监控焦点变化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆