MFC-GetTopWindow获取指定窗口的子窗口中最顶层的窗口句柄

发布时间 2023-04-26 09:03:45作者: 天子骄龙

 

    //GetTopWindow
    HWND hWnd = ::FindWindow(_T("#32770"), _T("测试程序"));
    if (!hWnd) {
        AfxMessageBox(_T("请打开测试程序"));
        ExitProcess(0);
    }
    CString str;
    str.Format(_T("主窗口句柄:hWnd=%d\r\n"), hWnd);
    ::OutputDebugString(str);

    HWND hWnd1 = ::FindWindowEx(hWnd, NULL, _T("Static"), _T("静态文本框"));
    str.Format(_T("静态文本框句柄:hWnd1=%d\r\n"), hWnd1);
    ::OutputDebugString(str);

    HWND hWnd2 = ::FindWindowEx(hWnd, NULL, _T("Edit"), NULL);
    str.Format(_T("编辑框句柄:hWnd2=%d\r\n"), hWnd2);
    ::OutputDebugString(str);

    HWND hWnd3 = ::FindWindowEx(hWnd, NULL, _T("Button"), _T("按钮"));
    str.Format(_T("按钮句柄:hWnd3=%d\r\n"), hWnd3);
    ::OutputDebugString(str);


    ::BringWindowToTop(hWnd2);
    
    HWND hWnd4 = ::GetTopWindow(hWnd);//获取指定窗口的子窗口中最顶层的窗口句柄
    /*
    参数:HWND hWnd 被查序的父窗口的句柄。如果该参数为NULL,函数返回Z序顶部的窗口句柄
    【这个函数只能用在同一个程序中父子窗口】
    */

    str.Format(_T("顶部窗口句柄:hWnd4=%d\r\n"), hWnd4);
    ::OutputDebugString(str);

    
    //返回的顶部窗口是编辑框

    ::BringWindowToTop(hWnd3);
    //把按钮放到Z序的顶部
    hWnd4 = ::GetTopWindow(hWnd);
    str.Format(_T("顶部窗口句柄:hWnd4=%d\r\n"), hWnd4);
    ::OutputDebugString(str);

    //返回的顶部窗口是编辑框

测试程序下载:

链接:https://pan.baidu.com/s/1f4e8R5wi6dnu-Ut4Hop5Vg
提取码:6666