Reputation: 17
I'm creating a dll file.
My code:
BOOL CALLBACK EnumWindowsProc(HWND hwnd, LPARAM lParam);
void test() {
EnumWindows(EnumWindowsProc, NULL);
}
BOOL CALLBACK EnumWindowsProc(HWND hwnd, LPARAM lParam)
{
char class_name[80];
char title[80];
GetClassName(hwnd, (LPWSTR) class_name, sizeof(class_name));
GetWindowText(hwnd, (LPWSTR) title,sizeof(title));
std::string titlas(title);
std::string classas(class_name);
Loggerc(titlas);
Loggerc("Gooing");
return TRUE;
}
Then I just call test()
.
In the log, titlas
is empty and code stops.
When I try this code in a Win32 app with CodeBlock, everything works, all of the titles show. But in a dll, it does not work.
Where is the problem?
Upvotes: 0
Views: 1050
Reputation: 42924
char class_name[80]; char title[80]; GetClassName(hwnd, (LPWSTR) class_name, sizeof(class_name)); GetWindowText(hwnd, (LPWSTR) title,sizeof(title)); std::string titlas(title); std::string classas(class_name);
Considering that since VS2005 the default has been building in Unicode mode (instead of ANSI/MBCS) and that you have those (ugly C-style) (LPWSTR)
casts, I'm assuming that you got compile-time errors when passing your char-based string buffers to APIs like GetClassName() and GetWindowText(), and you tried to fix those errors with casts.
That's wrong. The compiler was actually helping you with those errors, so please follow its advice instead of casting the compiler errors away.
Assuming Unicode builds, you may want to use wchar_t
and std::wstring
instead of char
and std::string
, and _countof()
instead of sizeof()
to get the size of buffers in wchar_t
s, not in bytes (char
s).
E.g.:
// Note: wchar_t used instead of char
wchar_t class_name[80];
wchar_t title[80];
// Note: no need to cast to LPWSTR (i.e. wchar_t*)
GetClassName(hwnd, class_name, _countof(class_name));
GetWindowText(hwnd, title, _countof(title));
// Note: std::wstring used instead of std::string
std::wstring titlas(title);
std::wstring classas(class_name);
If other parts of your code do use std::string
, you may want to convert from UTF-16-encoded text stored in std::wstring
(returned by Windows APIs) to UTF-8-encoded text and store it in std::string
instances.
Upvotes: 2