一种方法是使用 Windows UI 自动化 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);
}
}
}
}
}