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?
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
andstd::wstring
instead ofchar
andstd::string
, and_countof()
instead ofsizeof()
to get the size of buffers inwchar_t
s, not in bytes (char
s).E.g.:
If other parts of your code do use
std::string
, you may want to convert from UTF-16-encoded text stored instd::wstring
(returned by Windows APIs) to UTF-8-encoded text and store it instd::string
instances.