Reputation: 94
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!
Upvotes: 1
Views: 7740
Reputation: 31394
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.
Upvotes: 1
Reputation: 7939
SendMessage(WM_GETTEXT) needs an array of chars for its LPARAM.
e.g.
const int nSize(80);
char szBuff[nSize] = "";
int nRet =
::SendMessage(hWnd, WM_GETTEXT, nSize, reinterpret_cast<LPARAM>(szBuff));
Upvotes: 0
Reputation: 49976
Change string text; to TCHAR (TCHAR will result to wchar_t on unicode builds) array:
TCHAR text[256];
SendMessage(windowHandle, WM_GETTEXT, sizeof(text)/sizeof(text[0]), LPARAM(text));
if you are using SendMessage to communicate with some unknown application its safer to use SendMessageTimeout, since this app can actually block on given message:
DWORD result;
::SendMessageTimeout(hwnd, WM_GETTEXT, sizeof(text)/sizeof(text[0]), LPARAM(text), 0, 1000, &result);
Upvotes: 1