L
L
Limons2021-11-04 20:49:35
C++ / C#
Limons, 2021-11-04 20:49:35

How to use the EnumWindows function?

Here is the code:

static BOOL CALLBACK enumWindowCallback(HWND func_hWnd, LPARAM lparam) {
  int length = GetWindowTextLength(func_hWnd);

  TCHAR* buffer;
  char* buffer = new char[length + 1];
  GetWindowText(hWnd, buffer, length + 1);
  string windowTitle(buffer);


  if (length != 0) {
    std::cout << func_hWnd << ":  " << windowTitle << std::endl;
  }
  return TRUE;
}


What's wrong?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
N
none7, 2021-11-05
@none7

#include <Windows.h>
#include <string>
#include <iostream>

using namespace std;

static BOOL CALLBACK enumWindowCallback(HWND func_hWnd, LPARAM lparam) {
    int length = GetWindowTextLengthA(func_hWnd);

    if (length != 0) {
        string windowTitle(length, '\0');
        GetWindowTextA(func_hWnd, windowTitle.data(), length + 1); // ANSI version and func_hWnd
        std::cout << func_hWnd << ":  " << windowTitle << std::endl;
    }
    return TRUE;
}

int main() {
    SetConsoleOutputCP(GetACP());
    EnumWindows((WNDENUMPROC)enumWindowCallback, 0);
    system("pause");
    return 0;
}

U
User700, 2021-11-04
@User700

The buffer variable is declared twice. Doing new without delete is a memory leak. I would implement this moment like this:

string title(length, '\0');
GetWindowText(hWnd, (char*)(title.data()), length+1);

And buffer then is not necessary.
In some standards, data does not return a const. a pointer, but it's easier to explicitly cast (see also const_cast).
But is it clear that this is only a callback for the function. You must call the WinAPI function itself by passing your callback to it.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question