gpt4 book ai didi

C++ 获取所有正在运行的进程及其名称

转载 作者:行者123 更新时间:2023-11-30 02:36:40 24 4
gpt4 key购买 nike

我目前正在用 C++ 开发一个项目,我想做的是获取所有正在运行的可用进程以及它们的标题,但目前我只能跟踪它们的处理程序并对它们进行计数,而不能拿走他们的头衔。

BOOL CALLBACK EnumWindowsProc(HWND hWnd, LPARAM lParam);
int i;
string hwndTitle;
LPTSTR WindowTitle;
int length = 0;
int getHWND()
{
std::cout << "Finding all open windows\n";
if(EnumWindows(EnumWindowsProc, 0)) {
std::cout << i << " windows are open\n"<<hwndTitle<<"\n"<<"Call was successful...\n" << std::endl;
std::cin.get();
} else {
std::cout << "Call was unsuccessful...\n" << std::endl;
std::cin.get();
}

return 0;
}

BOOL CALLBACK EnumWindowsProc(HWND hWnd, LPARAM lParam) {
i++;
HWND WindowHandle;
WindowHandle = GetForegroundWindow();
length = GetWindowTextLength (hWnd);
hwndTitle = GetWindowText(hWnd , WindowTitle , length);
return true;
}

最佳答案

您的代码滥用了 GetWindowText()。您没有为其分配任何内存来填充,并且它不返回 std::string 甚至 char*/TCHAR*,就像您的代码假设的那样。即使您正确使用它,您也只会输出分配给 hwndTitle 的最后一个窗口标题,而不是将多个标题连接在一起。

尝试更像这样的东西:

BOOL CALLBACK EnumWindowsProc(HWND hWnd, LPARAM lParam);

int getHWND()
{
std::cout << "Finding all open windows" << std::endl;
int i = 0;
if (EnumWindows(EnumWindowsProc, (LPARAM) &i)) {
std::cout << i << " windows are open\n" << "Call was successful...\n" << std::endl;
} else {
std::cout << "Call was unsuccessful...\n" << std::endl;
}
std::cin.get();
return 0;
}

BOOL CALLBACK EnumWindowsProc(HWND hWnd, LPARAM lParam)
{
int *i = (int*) lParam;
++(*i);
int length = GetWindowTextLengthA(hWnd);
std::vector<char> WindowTitle(length+1);
length = GetWindowTextA(hWnd, &WindowTitle[0], length);
if (length > 0) {
WindowTitle[length] = 0;
std::cout << &WindowTitle[0] << std::endl;
} else {
std::cout << "(none)" << std::endl;
}
return TRUE;
}

或者:

BOOL CALLBACK EnumWindowsProc(HWND hWnd, LPARAM lParam);

int getHWND()
{
std::cout << "Finding all open windows" << std::endl;
std::vector<std::string> WindowTitles;
if (EnumWindows(EnumWindowsProc, (LPARAM) &WindowTitles)) {
for (std::vector<std::string>::iterator i = WindowTitles.begin(); i != WindowTitles.end(); ++i) {
if (!i->empty()) {
std::cout << *i << std::endl;
} else {
std::cout << "(none)" << std::endl;
}
}
std::cout << WindowTitles.size() << " windows are open\n" << "Call was successful...\n" << std::endl;
} else {
std::cout << "Call was unsuccessful...\n" << std::endl;
}
std::cin.get();
return 0;
}

BOOL CALLBACK EnumWindowsProc(HWND hWnd, LPARAM lParam)
{
std::vector<std::string> *WindowTitles = (std::vector<std::string>*) lParam;
int length = GetWindowTextLengthA(hWnd);
std::string WindowTitle(length+1, '\0');
length = GetWindowTextA(hWnd, &WindowTitle[0], length);
WindowTitle.resize(length);
WindowTitles->push_back(WindowTitle);
return TRUE;
}

关于C++ 获取所有正在运行的进程及其名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32464552/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com