Guy Pnini
Guy Pnini

Reputation: 21

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);
}

Upvotes: 0

Views: 662

Answers (2)

NTDLS
NTDLS

Reputation: 4862

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);
}

Upvotes: 3

Landstalker
Landstalker

Reputation: 1368

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();

Upvotes: 0

Related Questions