5

我使用此代码来获取窗口名称:

#include <Windows.h>
#include <stdio.h>

int main() {
    TCHAR title[500];
    int i=0;
    while(i<10) {
        GetWindowText(GetForegroundWindow(), title, 500);
        printf("%s\n",title);
        i++;
        system("pause");
    }
}

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

  1. 我需要获取所有窗口名称

  2. 或者,实际上,我需要获取一个属于“notepad.exe”进程的特定窗口名称。

谢谢你的帮助 :)

4

3 回答 3

8

我不认为使用原始 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'\0');
            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 << "\n\n";
        }
    }

    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 中工作,并且不能覆盖额外的空字符(不是长度的一部分)。最后,我们返回TRUE以便它继续枚举,直到它通过每个顶级窗口。

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

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

于 2012-12-25T10:34:32.920 回答
3

打电话EnumWindows。您提供一个回调函数,该函数为每个顶级窗口调用一次。然后,您可以使用您的特定标准检查每个窗口的属性。您可以调用GetWindowText,然后根据您要查找的值进行检查。

于 2012-12-25T11:36:18.317 回答
0

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

你问,

“我需要获取一个属于“notepad.exe”进程的特定窗口名称”

好吧,C++ 是该任务的错误语言。这是一项通过脚本更自然、更简单的任务。例如,这是一个报告所有记事本窗口标题的 Windows 批处理文件:

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

示例使用:

[d:\dev\misc\so\notepad_window_name]
>标题
“无标题 - 记事本”

[d:\dev\misc\so\notepad_window_name]
> _

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

此外,除了语言选择之外,请考虑您的 C++ 代码通过其使用TCHAR类型来宣传,它可以编译为 Unicode 和 ANSI——但由于使用printf. 这意味着过于愚蠢的TCHAR做法会误导您引入错误。简单地不要使用这些T东西,比如TCHAR:它只是一种混淆代码和引入错误的方法。

下面的代码举例说明了如何创建一个纯 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'\0' );
            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++ 形式的代码,并且确实需要所有记事本窗口标题,那么批处理文件将无法使用,而上述 C++ 代码也无法使用。在这种情况下,请按照 David Hefferman的建议使用 Windows EnumWindowsAPI 函数。并且为了避免混淆、细微的错误和误导阅读代码的其他人,请使用基于字符串,而不是,如上面的代码所示。wchar_tTCHAR

于 2012-12-25T13:43:51.003 回答