我目前正在尝试获取所有打开的窗口的列表并将它们存储在向量中。我一直在查看代码,以至于解决方案可能非常简单,但如果没有全局变量(我想避免),我似乎无法完成它。
这是代码:
#include "stdafx.h"
#include "json.h"
#include <algorithm>
using namespace std;
vector<string> vec;
BOOL CALLBACK speichereFenster(HWND hwnd, LPARAM substring){
const DWORD TITLE_SIZE = 1024;
TCHAR windowTitle[TITLE_SIZE];
GetWindowText(hwnd, windowTitle, TITLE_SIZE);
int length = ::GetWindowTextLength(hwnd);
wstring temp(&windowTitle[0]);
string title(temp.begin(), temp.end());
if (!IsWindowVisible(hwnd) || length == 0 || title == "Program Manager") {
return TRUE;
}
vec.push_back(title);
return TRUE;
}
int main() {
EnumWindows(speichereFenster, NULL);
cin.get();
return 0;
}
我想将所有标题存储在向量中,但我不知道如何存储,因为我无法将向量传递到函数中......
谢谢!!!
第二个参数(lParam) to 枚举窗口 https://msdn.microsoft.com/en-us/library/windows/desktop/ms633497.aspx记录为:
要传递给回调函数的应用程序定义的值。
只需将您的容器传递给 API 调用即可:
int main() {
std::vector<std::wstring> titles;
EnumWindows(speichereFenster, reinterpret_cast<LPARAM>(&titles));
// At this point, titles if fully populated and could be displayed, e.g.:
for ( const auto& title : titles )
std::wcout << L"Title: " << title << std::endl;
cin.get();
return 0;
}
并在回调中使用它:
BOOL CALLBACK speichereFenster(HWND hwnd, LPARAM lParam){
const DWORD TITLE_SIZE = 1024;
WCHAR windowTitle[TITLE_SIZE];
GetWindowTextW(hwnd, windowTitle, TITLE_SIZE);
int length = ::GetWindowTextLength(hwnd);
wstring title(&windowTitle[0]);
if (!IsWindowVisible(hwnd) || length == 0 || title == L"Program Manager") {
return TRUE;
}
// Retrieve the pointer passed into this callback, and re-'type' it.
// The only way for a C API to pass arbitrary data is by means of a void*.
std::vector<std::wstring>& titles =
*reinterpret_cast<std::vector<std::wstring>*>(lParam);
titles.push_back(title);
return TRUE;
}
Notes:
- 所提供的代码使用
std::wstring
代替std::string
。这是必须的,以便可以表示整个字符集。
- As written, the code isn't correct. There are (invisible) code paths, that have no well-defined meaning. The Windows API is strictly exposed as a C interface. As such, it doesn't understand C++ exceptions. Particularly with callbacks it is vital to never let C++ exceptions travel across unknown stack frames. To fix the code apply the following changes:
- [仅限 C++11] 标记回调noexcept https://en.cppreference.com/w/cpp/language/noexcept_spec.
- 将整个回调包装在一个试着抓 https://en.cppreference.com/w/cpp/language/try_catch阻止并适当处理任何异常。
- [仅限 C++11] 使用 C++11,您可以通过传递 a 来跨未知堆栈帧传递 C++ 异常std::Exception_ptr https://en.cppreference.com/w/cpp/error/exception_ptr,并调用std::rethrow_Exception https://en.cppreference.com/w/cpp/error/rethrow_exception在呼叫站点。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)