在c++中获取特定的窗口名称

getting a specific window name in c++

本文关键字:窗口 c++ 获取      更新时间:2023-10-16

我使用以下代码获取窗口名称:

#include <Windows.h>
#include <stdio.h>
int main() {
    TCHAR title[500];
    int i=0;
    while(i<10) {
        GetWindowText(GetForegroundWindow(), title, 500);
        printf("%sn",title);
        i++;
        system("pause");
    }
}

但是,它只获得前景窗口。

  1. 我需要得到所有的窗口名称

  2. 或者,实际上,我需要得到一个属于"notepad.exe"进程的特定窗口名称。

谢谢你的帮助

我不认为使用原始的winapi真的有什么更简单的方法,但是这里是:

  1. 使用Toolhelp32 API获取可执行文件名与"notepad.exe"匹配的进程id列表。
  2. 枚举窗口以查找PID与列表中匹配的窗口。
  3. 获取该窗口的标题,并做你想做的。

下面是我想出来的代码:

#include <iostream>
#include <string>
#include <vector>
#include <windows.h>
#include <tlhelp32.h>
bool isNotepad(const PROCESSENTRY32W &entry) {
    return std::wstring(entry.szExeFile) == L"notepad.exe";
}
BOOL CALLBACK enumWindowsProc(HWND hwnd, LPARAM lParam) {
    const auto &pids = *reinterpret_cast<std::vector<DWORD>*>(lParam);
    DWORD winId;
    GetWindowThreadProcessId(hwnd, &winId);
    for (DWORD pid : pids) {
        if (winId == pid) {
            std::wstring title(GetWindowTextLength(hwnd) + 1, L'');
            GetWindowTextW(hwnd, &title[0], title.size()); //note: C++11 only
            std::cout << "Found window:n";
            std::cout << "Process ID: " << pid << 'n';
            std::wcout << "Title: " << title << "nn";
        }
    }
    return TRUE;
}
int main() {
    std::vector<DWORD> pids;
    HANDLE snap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
    // Do use a proper RAII type for this so it's robust against exceptions and code changes.
    auto cleanupSnap = [snap] { CloseHandle(snap); };
    PROCESSENTRY32W entry;
    entry.dwSize = sizeof entry;
    if (!Process32FirstW(snap, &entry)) {
        cleanupSnap();
        return 0;
    }
    do {
        if (isNotepad(entry)) {
            pids.emplace_back(entry.th32ProcessID);
        }
    } while (Process32NextW(snap, &entry));
    cleanupSnap();
    EnumWindows(enumWindowsProc, reinterpret_cast<LPARAM>(&pids));
}

按顺序浏览:

首先注意函数和字符串的广泛版本。TCHAR不好用,如果其中一个标题碰巧有UTF-16,那就太可惜了。

isNotepad只是检查PROCESSENTRY32W结构的可执行文件名成员,看它是否等于"notepad.exe"这里假设记事本使用这个进程名,并且记事本之外的任何东西都不会使用这个进程名。为了消除误报,你必须做更多的检查,但你永远不能太确定。

enumWindowsProc中,请注意lParam实际上是指向pid向量的指针(为了避免使用全局变量)。这构成了函数开始时的强制转换。接下来,我们获得找到的窗口的PID。然后,循环遍历传入的pid列表并检查它是否匹配。如果是这样,我选择获取标题并输出PID和窗口标题。请注意,使用标准字符串作为缓冲区只能保证在c++ 11中工作,并且不能覆盖额外的null字符(不是长度的一部分)。最后,我们返回TRUE,以便它继续枚举,直到它遍历每个顶级窗口。

main上,您首先看到的是我们最初的空pid列表。我们对流程进行快照,并逐一进行检查。我们使用辅助函数isNotepad来检查进程是否为"notepad.exe",如果是,则存储其PID。最后,我们调用EnumWindows来枚举窗口,并传入pid列表,伪装成所需的LPARAM

如果你没有做过这种事情,这有点棘手,但我希望这是有意义的。如果您想要子窗口,正确的做法是添加EnumChildWindowsProc,并在我输出关于找到的窗口的信息的位置调用EnumChildWindows。如果我是正确的,你不需要递归地调用EnumChildWindows来获得孙子等,因为它们将包含在第一次调用中。

呼叫EnumWindows。您提供了一个回调函数,该函数对每个顶级窗口调用一次。然后,您可以使用您的特定条件检查每个窗口的属性。你可以调用GetWindowText,然后检查你正在寻找的值

如何获取记事本窗口的标题。

你问

,

我需要得到一个属于"notepad.exe"进程的特定窗口名称

好吧,c++不适合这个任务。通过编写脚本,这是一项更自然、更简单的任务。例如,下面是一个Windows批处理文件,它报告所有Notepad窗口的标题:

@echo off
for /f "usebackq delims=, tokens=1,9" %%t in (`tasklist /v /fo csv`) do (
    if %%t=="notepad.exe" echo %%u
    )

使用例子:<>之前[d: 开发 misc notepad_window_name]> <我> 标题"无题-记事本"[d: 开发 misc notepad_window_name]> _之前


如何编写现代Unicode c++ Windows程序。

此外,除了语言选择之外,考虑到您的c++代码通过使用TCHAR类型来宣传,它可以被编译为Unicode和ANSI –但由于使用printf,它不能被编译为Unicode。这意味着过于愚蠢的TCHAR误导您引入了一个bug。不要像TCHAR那样使用T:这只会混淆代码并引入bug。

下面的代码举例说明了如何创建一个纯unicode程序。

与批处理文件相比,这只检索一个记事本窗口的标题:

#include <iostream>     // std::wcout, std::endl
#include <stdlib.h>     // EXIT_FAILURE, EXIT_SUCCESS
#include <string>       // std::wstring
using namespace std;
#define UNICODE
#include <windows.h>
int main()
{
    HWND const window = FindWindow( L"Notepad", nullptr );
    if( window == 0 )
    {
        wcerr << "!Didn't find any Notepad window." << endl;
    }
    else
    {
        int const   nAttempts   = 3;
        for( int i = 1;  i <= nAttempts;  ++i )
        {
            int const   bufferSize  = 1 + GetWindowTextLength( window );
            wstring     title( bufferSize, L'' );
            int const   nChars  = GetWindowText( window, &title[0], bufferSize );
            if( nChars == 0 || nChars < GetWindowTextLength( window ) )
            {
                Sleep( 20 );  continue;
            }
            title.resize( nChars );
            wcout << "'" << title << "'" << endl;
            return EXIT_SUCCESS;
        }
        wcerr << "!Found a Notepad window but unable to obtain the title." << endl;
    }
    return EXIT_FAILURE;
}

因此,c++是错误的语言选择,TCHAR是完全错误的数据类型选择。


当其他需求迫使语言选择时如何使用c++。

如果出于某种原因,确实需要像c++那样的代码,并且确实需要所有的Notepad窗口标题,那么批处理文件不需要,上面的c++代码也不需要。在这种情况下,请按照David Hefferman的建议使用Windows EnumWindows API函数。为了避免混淆,微妙的错误和误导其他人阅读代码,请使用基于wchar_t的字符串,而不是TCHAR,如上面的代码所示。