如何监控焦点变化?

时间:2012-07-29 17:33:53

标签: c# c++ vb.net vbscript batch-file

好吧有时候我正在打字,而且很少发生某些东西偷了重点,我读了一些解决方案(甚至是VB手表),但它们并不适用于我。是否有任何窗口范围的“手柄”可以处理任何焦点变化?

无论使用哪种语言,C,C ++,VB.NET,C#,Anything .NET或Windows相关,Batch,PoweShell,VBS Script ...只要我能够监控每个焦点变化和将其记录到文件/ cmd窗口/可视窗口中。

类似的东西:

   void event_OnWindowsFocusChange(int OldProcID, int NewProcID);

非常有用。或者也许有这方面的工具(我找不到?)

2 个答案:

答案 0 :(得分:16)

一种方法是使用Windows UI Automation API。它揭示了一个全球焦点变化的事件。这是我想出的一个快速示例(在C#中)。注意,您需要添加对UIAutomationClient和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);
                }
            }
        }
    }
}

答案 1 :(得分:1)

您可以使用钩子监视焦点更改。 SetWindowsHookEx(),使用WH_SHELL钩子完成它。回调获取HSHELL_WINDOWACTIVATED通知。

这并不容易,特别是在托管语言中,因为它需要一个可以注入的DLL。你也不能可靠地分辨出预期的焦点变化或推动窗口的过程与偷走焦点之间的区别。哪个Windows试图阻止,但有一个名为AttachThreadInput()的后门欺骗了该代码。

要知道这是什么过程并不难。毕竟,它试图激活其中一个窗口。卸载该程序是一个简单而且最好的解决方法。

相关问题