Error : Cannot convert char to wchat_t*

207 Views Asked by At

Im trying to get the active window title using GetForegroundWindow and GetWindowText Functions and this is my code

HWND hwnd = GetForegroundWindow();
char wname[255];
GetWindowText(hwnd,wname,255);

And Everytime i try to build the project i get this error message "Error : Error : Cannot convert char to wchat_t*"

Im using c++builder xe7

So, What's wrong?

2

There are 2 best solutions below

6
acwaters On BEST ANSWER

You're building your application in Unicode-aware mode; a char is not large enough to hold a UTF-16 character. The type system is saving you from a lot of potential headache here by catching this for you. Either change to ASCII mode (easy but bad solution), switch to using wide strings everywhere (annoying solution), or use the provided macros to choose at compile time based on build parameters (even more annoying but most correct solution).

This is what this code snippet would look like with either of the above solutions implemented:

HWND hwnd = GetForegroundWindow();
wchar_t wname[255];
GetWindowText(hwnd, wname, 255);

HWND hwnd = GetForegroundWindow();
TCHAR wname[255];
GetWindowTextW(hwnd, wname, 255);

If you choose to build a Unicode-aware application (which you should), you must also remember to use wmain or _tmain as applicable, rather than plain old boring main. Because Windows.

0
Remy Lebeau On

You are calling the TCHAR version of GetWindowText(). In your Project Options, you have the "TCHAR maps to" option set to wchar_t, so GetWindowText() maps to GetWindowTextW(), which takes a wchar_t* parameter. That is why you cannot pass in a char[] buffer.

So, you need to either:

  1. Change "TCHAR maps to" to char so that GetWindowText() maps to GetWindowTextA() instead (also similarly affects every other TCHAR-based API function call in your code. Use this approach only when migrating legacy pre-Unicode code to C++Builder 2009+).

  2. Change your code to use TCHAR instead:

    TCHAR wname[255];
    GetWindowText(hwnd,wname,255);
    
  3. Change your code to use the Ansi or Unicode version of GetWindowText() directly:

    char wname[255];
    GetWindowTextA(hwnd,wname,255);
    

    wchar_t wname[255];
    GetWindowTextW(hwnd,wname,255);