首页 > 解决方案 > 如何在 C++ 中使用 FindWindow 在 unicode 中搜索

问题描述

FindWindowW(NULL, "program name")在使用函数时,我一直在寻找中文程序名称。

当我搜索英语时,它工作得很好。

有人可以告诉我如何使用 unicode 进行搜索吗?

我还想不通,谁能指导我怎么做?

#include <windows.h>
#include <stdio.h>

int main(){
    HWND hWnd = FindWindowW(NULL,L"\uAA5A\uAA4C\uB873\uAB4C\uB6C7");

    if(NULL == hWnd){
        printf("NotFound!");
    }else {
        printf("Found!");
    }
   }

标签: c++unicode

解决方案


使用 FindWindow 的 Unicode(宽)版本并使用宽字符串进行搜索。我还建议将源代码保存为 UTF-8 编码并使用/utf-8Microsoft 编译器的编译器开关;否则,编译器将采用本地化的 ANSI 编码来解释宽字符串。如果您的本地化编码是中文变体,那很好,但如果您使用的是美国或西欧版本的 Windows,如果您在字符串常量中使用中文字符,Microsoft IDE 可能会提示您以 UTF-16 保存:

例子:

#include <windows.h>
#include <stdio.h>

int main(void)
{
    //HWND h = FindWindowW(NULL,L"马克"); // works if saved in UTF-8 encoding
    //                                    // and compiled with /utf-8.

    HWND h = FindWindowW(NULL,L"\u9a6c\u514b");

    if(h == NULL)
        printf("err = %ld\n",GetLastError());
    else
        printf("handle = %p\n",h);
}

在 Windows 上,我将终端窗口更改为匹配的中文标题,title 马克这段代码找到了窗口:

C:\>title 马克

C:\>test
handle = 00000000000B0258

C:\>test
handle = 00000000000B0258

微软的 Spy++ 工具确认句柄: 具有匹配句柄的 Spy++ 数据


推荐阅读