从"DWORD"到"常量字符*"的转换无效

Invalid conversion from 'DWORD' to 'const char *'

本文关键字:转换 无效 常量 DWORD 字符      更新时间:2023-10-16

我试图编译一些代码,但遇到了一个错误:

错误从DWORDconst 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可能太小,或者比必要的大——这取决于您和您的情况)。