0

I wrote the following code one year ago to return a list of all the current windows

#include <iostream>
#include <windows.h>

using namespace std;

BOOL CALLBACK EnumWindowsProc(HWND hwnd, LPARAM lParam)
{
    TCHAR buffer[512];
    SendMessage(hwnd, WM_GETTEXT, 512, (LPARAM)(void*)buffer);
    cout << buffer << endl;
    return TRUE;
}

int main()
{
    EnumWindows(EnumWindowsProc, NULL);
    return 0;
}

This code worked when i originally wrote it, however now the result list I am getting is not what I expected.

I am getting the following text repeated around 40 times.

...
0031F6F0
0031F6F0
0031F6F0
0031F6F0
0031F6F0
0031F6F0
0031F6F0
...

How can I change the 0031F6F0 to read each window name instead of the above, and also why would the code result have changed?

JackBoy
  • 61
  • 4
  • 3
    The `EnumWindowsProc` signature is wrong. The second parameter should be `LPARAM`, not `LONG`. You also should not be casting `buffer` to `void*`, and `sizeof(buffer)` is wrong because it returns the size in bytes, not the number of characters. That should be 512 (or `sizeof(buffer)/sizeof(buffer[0])`). This code should never have worked correctly. – Cody Gray - on strike Jan 11 '17 at 20:09
  • @CodyGray Thanks I have updated my code both here and on my PC. I still have the binary which works from the above original code(before your corrections) – JackBoy Jan 11 '17 at 20:12
  • How are you compiling this? With MinGW C++ I get the expected results - a list of window captions. –  Jan 11 '17 at 20:26
  • 4
    You changed a project setting. Project > Properties > General > Character Set. So now you have to use wcout instead of cout. Do stop using TCHAR. – Hans Passant Jan 11 '17 at 20:27
  • 3
    It appears that `cout` is interpreting `buffer` as a pointer rather than a string. If you have a Unicode build (and so `TCHAR` is actually `wchar_t`) you should use `wcout` instead. – Jonathan Potter Jan 11 '17 at 20:27
  • What @JonathanPotter said ^^. Sounds like you stepped up to a Unicode build. – RamblinRose Jan 11 '17 at 20:33
  • 1
    Surely you aren't needing to support Windows 98. – David Heffernan Jan 11 '17 at 21:09
  • I originally compiled this last year with codeblocks, today I compiled this with Visual Studio, which may explain why it didnt work. After changing `cout` to `wcout` like suggested above the script works. – JackBoy Jan 12 '17 at 01:34

0 Answers0