1

我试图让一个函数找到一个窗口句柄。在以下方式之前,我已经多次这样做了:

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

但是,我随后尝试执行以下操作:

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

并出现以下错误:

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

我有另一个函数给 myString 一个值,所以我想将该值作为变量传递给 FindWindow() 函数,但是这个错误即将出现,我不明白发生了什么。

问题:: 为什么我会收到此错误,如何将字符串变量放入 FindWindow() 函数?

4

2 回答 2

3

为什么会出现此错误,如何将字符串变量放入 FindWindow() 函数?

编译器错误消息非常清楚。该FindWindow()函数需要一个const char*作为第二个参数,但std::string事实并非如此。
要获得const指向由std::string实例管理的原始 char 数组数据的 () 指针,请使用以下c_str()方法:

FindWindow(NULL, myString.c_str()); 
于 2014-04-29T15:00:44.860 回答
0

问题是您试图将类型的对象传递std::string给需要 a LPCSTR(这是 的别名const char*)的函数,但std::string不会隐式转换为const char*,因此您会收到错误消息。要使函数工作,您需要传递一个 C 风格的字符串 ( const char*),您可以通过传递myString.c_str()而不是传递myString.

于 2014-04-29T15:02:22.950 回答