C++ – SendMessage WM_GETTEXT error


I am trying to make a program that will get the name of window of another program. For that, I want to use the SendMessage() function with the WM_GETTEXT message. I know however that I am probably doing a lot of things wrong so here is the code I used:

string text;
SendMessage(windowHandle, WM_GETTEXT, sizeof(text), LPARAM(text));

I am pritty sure that… I probably have a lot of stuff wrong. The LPARAM(text) is probably dead wrong since in MSDN it says that this parameter is: A pointer to the buffer that is to receive the text.

Problem is… I have no idea what a buffer is and how to declare it… and how to convert it into a string variable with the name of the window inside it.

The error I got was:

error: invalid cast from type 'std::string {aka std::basic_string<char>}' to type 'LPA {aka long int}'

the error is for the line with SendMessage. So my questions are:

What am I doing wrong? What is a buffer? How do I declare a buffer? How do I convert that buffer into a text file?
If someone can show me code that does what I want… that would probably be the best answer I could ask for!

Best Solution

The Win32 API is a C api, you can't use a C++ string with it. You need to use a char buffer instead:

char text[256];
LRESULT result = SendMessage(windowHandle, WM_GETTEXT, sizeof(text), LPARAM(text));

Also sizeof(text) when text of a string doesn't do what you want. sizeof gives the number of bytes a uses, which for a string is not the number of characters in the buffer since a string dynamically allocates its buffer.

Finally casting a string to an LPARAM, that is an integer doesn't make any sense. In general there is no way to convert a C++ object to an integer.

Related Question