user352258
user352258

Reputation: 45

Converting TCHAR to a char* for strstr function

    char skype[6] = "Skype";
    HWND firstwindow = FindWindowEx(NULL, NULL, NULL, NULL);
    HWND window = firstwindow;
    TCHAR windowtext[MAX_PATH]; //search term

    //We need to get the console title in case we
    //accidentally match the search word with it
    //instead of the intended target window.
    TCHAR consoletitle[MAX_PATH];
    GetConsoleTitle(consoletitle, MAX_PATH);

    while(true){
        //Check window title for a match
        GetWindowText(window, windowtext, MAX_PATH);
        if (strstr(windowtext, skype)!=NULL && strcmp(windowtext, consoletitle)!=0) break; //search for program
            //Get next window
            window = FindWindowEx(NULL, window, NULL, NULL);
        if(window == NULL || window == firstwindow){
            printf("Window not found.\n");
            return 1;
        }
    } //end while
Error: cannot convert 'TCHAR* {aka wchar_t*}' to 'const char*' for argument '1' to 'char* strstr(const char*, const char*)'

Problem occurs at this line:

if (strstr(windowtext, skype)!=NULL && strcmp(windowtext, consoletitle)!=0) break; //search for program

I don't have a problem when I run the same program in cygwin mingw32gcc compiler. Is this a issue with me using QT mingw32gcc compiler? I have included <windows.h> at the very beginning so that's not the issue.

Edit: Ok So I've added <tchar.h> and substituted if (_tcsstr(windowtext, skype)!=NULL && _tcscmp(windowtext, consoletitle)!=0) break;

But the problem still persists: Error: cannot convert 'TCHAR* {aka wchar_t*}' to 'const char*' for argument '1' to 'char* strstr(const char*, const char*)'

Upvotes: 0

Views: 2530

Answers (2)

ahmed
ahmed

Reputation: 5600

To use unicode in you code you need to define UNICODE and _UNICODE preprocessor macros before compiling you code, so add this command line arguments to you compiling command:

-DUNICODE -D_UNICODE

for more you can read this:
http://www.cplusplus.com/forum/windows/90069

Upvotes: 0

Drew McGowen
Drew McGowen

Reputation: 11706

Instead of converting to char * to use in strstr, you should use the TCHAR-equivalent, _tcsstr; it'll compile to the correct call to either strstr or wcsstr.

Upvotes: 7

Related Questions