将参数转换为LPWSTR CreateProcess

时间:2019-02-18 03:04:41

标签: c++

我正在尝试使用cmd.exe执行某些操作,但是我想隐藏cmd.exe。当我尝试使用完整路径而不是cmd.exe时,总是会出现此错误:

char Process[] = "C:\\WINDOWS\\System32\\cmd.exe";
                STARTUPINFO sinfo;
                PROCESS_INFORMATION pinfo;
                memset(&sinfo, 0, sizeof(sinfo));
                sinfo.cb = sizeof(sinfo);
                sinfo.dwFlags = (STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW);
                sinfo.hStdInput = sinfo.hStdOutput = sinfo.hStdError = (HANDLE)mySocket;
                CreateProcess(NULL, Process, NULL, NULL, TRUE, 0, NULL, NULL, &sinfo, &pinfo);
                WaitForSingleObject(pinfo.hProcess, INFINITE);
                CloseHandle(pinfo.hProcess);
                CloseHandle(pinfo.hThread);

我总是得到:

CreateProcessW(LPCWSTR,LPWSTR,LPSECURITY_ATTRIBUTES,LPSECURITY_ATTRIBUTES,BOOL,DWORD,LPVOID,LPCWSTR,LPSTARTUPINFOW,LPPROCESS_INFORMATION)':无法将参数2从'char [28]'转换为'LPWSTR'ConsoleApplication1 < / em>

1 个答案:

答案 0 :(得分:3)

您传递的是窄字符数组而不是宽字符数组。

将项目的字符编码设置更改为MultiByte而不是Unicode,以便CreateProcess使用CreateProcessA而不是CreateProcessW

或者,使用wchar_t(或WCHAR,这是Windows中可用于wchar_t的typedef)而不是char

wchar_t Process[] = L"C:\\WINDOWS\\System32\\cmd.exe";

或者,您可以更改代码以手动使用CreateProcessA

char Process[] = "C:\\WINDOWS\\System32\\cmd.exe";
...
CreateProcessA(NULL, Process, NULL, NULL, TRUE, 0, NULL, NULL, &sinfo, &pinfo);
...