سؤال

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?

هل كانت مفيدة؟

المحلول

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()); 

نصائح أخرى

The problem is that you are trying to pass an object of type std::string into a function requiring a LPCSTR (which is an alias for const char*), but std::string doesn't implicitly convert to const char* and therefore you get the error message. To get the function to work, you'll need to pass a C-style string (const char*), which you do by passing myString.c_str() instead of myString.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top