c++winapic++builder-xe

Error : Cannot convert char to wchat_t*


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?


Solution

  • 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.