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

Windows 11系统托盘应用数量获取失败求助(Win10代码失效)

Windows 11中获取系统托盘应用数量的解决方法

问题背景

此前在Windows 10中可正常获取系统托盘应用数量的代码,在Windows 11中失效,运行后返回值为0,TB_BUTTONCOUNT消息返回0。原代码如下:

int GetTrayAppCount()
{
    HWND hWndTray   = NULL;
    int  nTrayCount = 0;

    // 统计隐藏托盘应用
    hWndTray = ::FindWindow( TEXT("NotifyIconOverflowWindow"),NULL );
    if( hWndTray ){
        if((hWndTray = ::FindWindowEx( hWndTray,NULL,TEXT("ToolbarWindow32"),NULL )){
            nTrayCount += (int)::SendMessage( hWndTray, TB_BUTTONCOUNT, 0,0 );
        }
    }

    // 统计可见托盘应用
    hWndTray = ::FindWindow( TEXT("Shell_TrayWnd"),NULL );
    if( hWndTray ){
        hWndTray = ::FindWindowEx( hWndTray,NULL,TEXT("TrayNotifyWnd"),NULL );
        if( hWndTray ){
            hWndTray = ::FindWindowEx( hWndTray,NULL,TEXT("SysPager"),NULL );
            if( hWndTray ){
                hWndTray = ::FindWindowEx( hWndTray,NULL,TEXT("ToolbarWindow32"),NULL );
                nTrayCount += (int)::SendMessage( hWndTray, TB_BUTTONCOUNT, 0,0 );
            }
        }
    }
    return nTrayCount;
}

问题原因

Windows 11重构了系统托盘的窗口结构:

  • 可见托盘图标不再嵌套在SysPager窗口下,而是直接位于TrayNotifyWnd的子窗口中,对应的ToolbarWindow32窗口文本为UserPromotedNotificationArea
  • 原代码的窗口查找路径已不符合Windows 11的UI结构,导致无法获取有效的Toolbar句柄,最终TB_BUTTONCOUNT返回0

修改后的代码

int GetTrayAppCount()
{
    HWND hWndTray = NULL;
    int nTrayCount = 0;

    // 统计隐藏托盘(溢出菜单)中的应用数量
    hWndTray = ::FindWindow(TEXT("NotifyIconOverflowWindow"), NULL);
    if (hWndTray) {
        hWndTray = ::FindWindowEx(hWndTray, NULL, TEXT("ToolbarWindow32"), NULL);
        if (hWndTray) {
            nTrayCount += static_cast<int>(::SendMessage(hWndTray, TB_BUTTONCOUNT, 0, 0));
        }
    }

    // 统计可见托盘的应用数量
    hWndTray = ::FindWindow(TEXT("Shell_TrayWnd"), NULL);
    if (hWndTray) {
        hWndTray = ::FindWindowEx(hWndTray, NULL, TEXT("TrayNotifyWnd"), NULL);
        if (hWndTray) {
            // Windows 11中可见托盘对应的Toolbar窗口,指定窗口文本定位
            hWndTray = ::FindWindowEx(hWndTray, NULL, TEXT("ToolbarWindow32"), TEXT("UserPromotedNotificationArea"));
            if (hWndTray) {
                nTrayCount += static_cast<int>(::SendMessage(hWndTray, TB_BUTTONCOUNT, 0, 0));
            }
        }
    }

    return nTrayCount;
}

注意事项

  • 确保程序以合适权限运行(如管理员权限),避免因窗口权限限制无法获取句柄
  • 若系统开启“小任务栏按钮”,UI结构可能略有差异,上述代码在默认设置下有效
  • 基于窗口类名、文本的查找方法依赖系统UI结构,若Windows版本更新调整UI,可能需要再次适配;追求长期稳定性建议使用官方Shell API(如IShellNotifyIcon相关接口,使用门槛较高)

内容的提问来源于stack exchange,提问作者toshi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 04:13:25