简体   繁体   中英

winApi create process using c++

I'm trying to open a picture using WinApi in c++, tried both createProcessW and createProcessA , my main problem was concatenating the strings that are used as cmdLine parameter. this is what iv'e got:

STARTUPINFOW process_startup_info{ 0 };
process_startup_info.cb = sizeof(process_startup_info); // setup size of strcture in bytes

PROCESS_INFORMATION process_info{ 0 };

wchar_t* s = L"\"C:\\Windows\\system32\\mspaint.exe\" ";
std::string s2 = pic.getPath();
// connecting strings here
if (CreateProcessW(NULL, /* string should be here */, NULL, NULL, TRUE, 0, NULL, NULL, &process_startup_info, &process_info))
{
    WaitForSingleObject(process_info.hProcess, INFINITE);
    CloseHandle(process_info.hProcess);
    CloseHandle(process_info.hThread);
}

Try to use the same types everywhere for the command and the params if you can. Here I am using a wstring , concatenating a parameter to the command then casting it to LPWSTR for the CreateProcess method.

STARTUPINFOW process_startup_info{ 0 };
process_startup_info.cb = sizeof(process_startup_info); // setup size of strcture in bytes

PROCESS_INFORMATION process_info{ 0 };

std::wstring params = L"\"C:\\Windows\\system32\\mspaint.exe\" ";
params.append(L"\"C:\\Vroom Owl.png\"");

// connecting strings here
if (CreateProcessW(NULL, (LPWSTR)params.data(), NULL, NULL, TRUE, 0, NULL, NULL, &process_startup_info, &process_info))
{
    WaitForSingleObject(process_info.hProcess, INFINITE);
    CloseHandle(process_info.hProcess);
    CloseHandle(process_info.hThread);
}

In include :

#include <sstream>

In code:

std::wstringstream wstringCmd;

std::wstring wstrExec = L"\"C:\\Windows\\system32\\mspaint.exe\" "; //<- wstring 
std::string strPic = pic.getPath(); //<- if getPath() return char  
// std::wstring wstrPic = pic.getPath();//<- if getPath() return wchar  

// you can combine as you like ...
wstringCmd << wstrExec.c_str() << strPic.c_str(); // or << wstrPic.c_str();
std::wstring wstrCommande= wstringCmd.str();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM