从"DWORD"到"常量字符*"的转换无效
Invalid conversion from 'DWORD' to 'const char *'
我试图编译一些代码,但遇到了一个错误:
错误从
DWORD
到const char *
的无效转换
以下是我试图编译的代码:
hWindow = FindWindow(NULL, "Window");
if (hWindow){
GetWindowThreadProcessId(hWindow, &pid);
}
hProcess = OpenProcess(PROCESS_ALL_ACCESS, 0, pid);
if(hProcess != NULL) {
SetWindowText(GetDlgItem(MyWindow, MyStatic), pid);
}
如何将DWORD
转换为const char *
?
SetWindowText
需要一个const char *
(即C字符串),而您正在向它传递一个数字(pid
),很明显您会得到一个错误。
执行转换的标准C++方法是使用字符串流(来自标头<sstream>
:
std::ostringstream os;
os<<pid;
SetDlgItemText(MyWindow, MyStatic, os.str().c_str());
(这里我使用了SetDlgItemText
而不是GetDlgItem
+SetWindowText
来保存键入,但这是一样的)
或者,您可以使用snprintf
。
char buffer[40];
snprintf(buffer, sizeof(buffer), "%u", pid);
SetDlgItemText(MyWindow, MyStatic, buffer);
在行中
SetWindowText(GetDlgItem(MyWindow, MyStatic), pid);
pid
是一个DWORD(正如您在GetWindowThreadProcessId(hWindow, &pid)
中使用的那样,它将LPDWORD
作为第二个参数)。但是,SetWindowText
需要一个C字符串作为它的第二个参数,因此您必须传递一个类型为char *
或char []
的值,而不是pid
。
要显示pid
的值,可以使用sprintf
:
char * str = new char[10];
sprintf(str,"%d",pid);
您可能需要稍微修改str
的大小(10可能太小,或者比必要的大——这取决于您和您的情况)。
相关文章:
- 错误:从"int"到枚举c++的转换无效
- 从 'int' 到 'int*' CPP 的转换无效
- C++ PTHREADS - 无效转换无效*(*)()到无效*(*)(无效*)
- 为什么我收到"从常量指针到指针的转换无效?
- 错误:从"int"到"int*"的转换无效[-允许].我在下面提供了我的代码,我
- 从类指针到 int 的转换无效
- C++ 错误:由于 swprintf 而从 'int' 到 'const wchar_t* 的转换无效
- 错误:从'void*'到'const uint8_t* {aka const unsigned char*}'的转换无效 [-允许]
- QTextStream的操作数到二进制的转换无效
- 从类型"void*"到函数指针的强制转换无效
- 错误:从 'char' 到 'const char' [-允许] strcat(加密,密钥[i])的转换无效;
- C++ - 从 "int" 到 "unsigned char" 的缩小转换无效
- 返回对象时从'const DList<int>* const'到 'DList<int>*' [-fallowive] 的转换无效
- 错误:AES 加密密钥:从"char*"到"无符号字符"的转换无效
- 模板类实例化中的指针转换无效
- 从"int"到"矢量*"的转换无效
- 从类型"void*"到类member_function指针的强制转换无效
- 在 sprintf 中从 'signed char*' 到 'char*' 的转换无效
- 另一个:从"常量类型*"到"类型*"的转换无效
- constexpr 链表 - 从 const X* 到 X* 的转换无效