Given an HWND, how can I cast to a String in C++?

598 Views Asked by At

I need to write a program in C++ that queries the OS for running Windows, find a Window with a specific window title, and return the Native Window Handle value as a String.

So far, I've figured out everything but the last part. I'm not too familiar with C++, as I'm writing this for a JS project as a NodeJS C++ addon, so I'd appreciate any help.

Here's the program so far:

static BOOL CALLBACK enumWindowCallback(HWND hWnd, LPARAM lparam) {
  int length = GetWindowTextLength(hWnd);
  char* buffer = new char[length + 1];
  GetWindowText(hWnd, buffer, length + 1);
  std::string windowTitle(buffer);

  if (IsWindowVisible(hWnd) && length != 0) {
    std::cout << hWnd << ":  " << windowTitle << std::endl;
    if (windowTitle.compare("Find This Window") == 0) {
      // Here is the confusion. I've found the right HWND, but I don't know how to cast the HWND to a String
      return FALSE;
     }
  }

  return TRUE;
}

int::main() {
  EnumWindows(enumWindowCallback, NULL);
}

On this line: std::cout << hWnd << ": " << windowTitle << std::endl;, the hWnd returns the hexadecimal value that I want. For example, it prints out: 0000000000100566: Find this App

The value preceding the : is the value I want to return as a String, but I can't figure out how. I've tried casting it, but it doesn't work.

Again, this is probably a simple solution, but I can't find it on the internet and my limited knowledge of C++ is hindering me.

1

There are 1 best solutions below

1
YangXiaoPo-MSFT On

Actually, the question is how to convert number to string.
At the beginning, as @KenWhite said, HWND is an opaque value.

#include <Windows.h>
#include <sstream>
void main()
{
    HWND i = FindWindow(NULL,NULL);
    char buffer[sizeof(HWND) * 2 + 1]{};
    _itoa_s((int)i, buffer, 16);

    std::ostringstream Convert;
    Convert << std::hex << i;
}