You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

焦点追踪变量lastFocusedWindow始终未更新且事件无预期输出的问题求助

焦点追踪变量lastFocusedWindow始终未更新且事件无预期输出的问题求助

大家好,我最近在开发一个Windows桌面应用,需要追踪系统中焦点窗口的变化,结果遇到了一个卡了我好久的问题:我试过各种调试手段,但lastFocusedWindow这个变量始终是0,完全没被更新过。更奇怪的是,就算控制台没输出"no changes",我也看不到预期的"change to: {0}"日志!

下面是我的完整代码,麻烦各位大佬帮我找找问题出在哪:

public partial class MainWindow : Window 
{ 
    private static volatile IntPtr lastFocusedWindow = IntPtr.Zero; 
    public MainWindow() 
    { 
        InitializeComponent(); 
        AllocConsole(); 
        this.Topmost = true; 
        Automation.AddAutomationFocusChangedEventHandler(OnFocusChangedHandler); 
    } 

    private void OnFocusChangedHandler(Object src, AutomationFocusChangedEventArgs args) 
    { 
        AutomationElement element = src as AutomationElement; 
        if (element == null) 
        { 
            return; 
        } 

        IntPtr hwnd = new IntPtr(element.Current.NativeWindowHandle); 
        if (hwnd == IntPtr.Zero || hwnd == (new WindowInteropHelper(this)).Handle) 
        { 
            Console.WriteLine("no changes"); 
            return; 
        } 

        lastFocusedWindow = hwnd; 
        Console.WriteLine("change to: {0}", hwnd); 
    } 

    private void SendKey(byte vk) 
    { 
        Console.WriteLine("last: {0}", lastFocusedWindow); 
        if (lastFocusedWindow != IntPtr.Zero) 
        { 
            SetForegroundWindow(lastFocusedWindow); 
            mutex.WaitOne(); 
            keybd_event(vk, 0, KEYEVENTF_EXTENDEDKEY, UIntPtr.Zero); 
            keybd_event(vk, 0, KEYEVENTF_KEYUP, UIntPtr.Zero); 
            mutex.ReleaseMutex(); 
        } 
    } 
}

我自己排查了一下,确认当前应用窗口的句柄判断是对的,切换其他窗口的时候,理论上应该触发焦点变化事件,但就是没看到对应的输出。而且在调用SendKey方法时,打印的lastFocusedWindow也一直是0,导致按键发送的逻辑根本走不起来。

有没有人遇到过类似的问题?或者能看出我的代码里有什么遗漏的地方吗?

内容来源于stack exchange

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.07 06:49:50