Search code examples
c++findwindow

C++ FindWindow() Issues


I am trying to make a function find a window handle. I have done this many times before the following way:

HWND windowHandle
windowHandle = FindWindow(NULL, "NameOfWindowIAmLookingFor");

However, I then tried to do the following:

string myString = "NameOfWindowIAmLookingFor";
HWND windowHandle
windowHandle = FindWindow(NULL, myString);

and the following error comes up:

error: cannot convert 'std::string {aka std::basic_string<char>)' to 'LPCSTR {aka const char*} ' for argument '2' to 'HWND__* FindWindowA(LPCSTR, LPCSTR)';

I have another function that is giving myString a value, so I want to pass that value as a variable to the FindWindow() function, but this error is coming up and I dont understand what is happening.

Question:: Why am I getting this error and how can I go about putting a string variable into the FindWindow() function?


Solution

  • Why am I getting this error and how can I go about putting a string variable into the FindWindow() function?

    The compiler error message is pretty clear. The FindWindow() function expects a const char* as second parameter, which std::string isn't.
    To get a (const) pointer to the raw char array data managed by a std::string instance use the c_str() method:

    FindWindow(NULL, myString.c_str());