Evaldas Jankauskas Evaldas Jankauskas - 3 months ago 25
C++ Question

EnumWindows not working

Im creating *.dll file.
Me 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()
at log titlas empty and code stop.

i try this all code on win32 with codeblock all work all titles show. But in dll not work, where is problem?

Answer
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_ts, not in bytes (chars).

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.