使用窗口标题的一部分获取processID

Get processID using part of WINDOW heading

本文关键字:获取 processID 一部分 窗口标题      更新时间:2023-10-16

我使用以下c++程序,在Visual c++ 6.0中,当MS Paint程序打开时用消息框通知我。它使用了MS Paint窗口的确切名称,即"无题-油漆"。然而,现在我需要使程序通知我与消息框时,我只知道实际窗口的名称的一部分,例如,如果窗口是"Abcdefgh -油漆",我设置字符串名称以这种方式- std::wstring windowName(L"油漆");-程序再次工作。使用以下3行代码,当实际窗口名称与MS Paint窗口的确切名称相同时,程序可以正常工作:

HWND windowHandle = FindWindowW(NULL, windowName.c_str());
DWORD* processID = new DWORD;
GetWindowThreadProcessId(windowHandle, processID);

但它不会工作,如果字符串windowName只是名称的一部分,我的意思是,如果它是"油漆"。有人能告诉我怎么做吗?我想把所有打开的窗口的名称列表,并与我的真实姓名的一部分进行比较,我的意思是在他们的名字中搜索子字符串"油漆"的匹配,但我不知道如何得到所有打开的窗口。另外,这一点很重要,我的电脑很旧,我使用的是Visual c++ 6.0,所以我不能使用c++的所有进化特性和现在的程序环境,我的意思是,我不能使用在。net中正确编译但在Visual c++ 6.0中不能编译的代码。由于

#include "stdafx.h"
#include < iostream>
#include < string>
#include < windows.h>
#include < sstream> 
#include < ctime>
int APIENTRY WinMain(HINSTANCE hInstance,
                 HINSTANCE hPrevInstance,
                 LPSTR     lpCmdLine,
                 int       nCmdShow)
{
// TODO: Place code here.
std::wstring windowName(L"Untitled - Paint");


while(true)
{
    Sleep(1000*5);
time_t t = time(0);   // get time now
struct tm * now = localtime( & t );
int tday = now->tm_mday;
int tmin = now->tm_min;
int thour = now->tm_hour;

HWND windowHandle = FindWindowW(NULL, windowName.c_str());
DWORD* processID = new DWORD;
GetWindowThreadProcessId(windowHandle, processID);
char probaintstr[20];
sprintf(probaintstr,"%d",*processID);


if(strlen(probaintstr) <=5 ) 
{
Sleep(1000*10);
MessageBox(NULL,"niama go Notepad ili Wordpad","zaglavie",MB_OK);
}
else {
}


}

return 0;
}

您可以使用EnumWindows,例如

BOOL CALLBACK enumWindow(HWND hwnd, LPARAM lp)
{
    std::string str(512, 0);
    int len = GetWindowText(hwnd, &str[0], str.size());
    if (str.find("Paint") != std::string::npos)
    {
        MessageBox(0, str.c_str(), 0, 0);
    }
    return true;
}
int APIENTRY WinMain(HINSTANCE, HINSTANCE, LPSTR, int)
{
    EnumWindows(enumWindow, 0);
    return 0;
}

或者您可以使用FindWindowEx并查找classname。MS Paint的类名为""MSPaintApp""。你可以从windows的"Spy"实用程序中找到这些信息。

int APIENTRY WinMain(HINSTANCE, HINSTANCE, LPSTR, int)
{
    for (HWND hwnd = NULL;;)
    {
        hwnd = FindWindowExA(NULL, hwnd, "MSPaintApp", 0);
        if (!hwnd)
            break;
        std::string str(512, 0);
        int len = GetWindowText(hwnd, &str[0], 512);
        str.resize(len);
        if (str.find("Paint") != std::string::npos)
            MessageBox(0, str.c_str(), 0, 0);
    }
    return 0;
}

对于进程id,不需要分配内存。只要使用引用:

DWORD processID;
GetWindowThreadProcessId(windowHandle, &processID);