c++winapicreateprocesswaitforsingleobject

The Command CreateProcess C++


The Command CreateProcess With the command WaitForSingleObject can to open an image? If Yes How can I open the image? I tried to open but i don't know Where to put the path to open

    if (CreateProcess(NULL, "C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Accessories\Paint.lnk", NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi))
    {
        WaitForSingleObject(pi.hProcess, INFINITE);

        CloseHandle(pi.hThread);
        CloseHandle(pi.hProcess);
    }

Solution

  • If you just want to open an existing image using defualt app then use ShellExectue API. For example:

    ShellExecuteW(NULL, L"open", L"Z:\\cat.PNG", NULL, NULL, SW_SHOW);
    

    You could also open image with mspaint using the same API:

    ShellExecuteW(NULL, L"open", L"C:\\Windows\\system32\\mspaint.exe", L"Z:\\cat.PNG", NULL, SW_SHOW);
    

    ShellExecuteEx will let you wait for finishing process.

    You can do the same using CreateProcess. As @DavidHeffernan pointed out the second parameter of CreateProcess should point to writable memory else it will raise access violation. To make it clear I will just omit the first parameter. Example:

    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 commandline_args[] = L"\"C:\\Windows\\system32\\mspaint.exe\" Z:\\cat.PNG";
    
    if (CreateProcessW(NULL, commandline_args, NULL, NULL, TRUE, 0, NULL, NULL, &process_startup_info, &process_info))
    {
        //WaitForSingleObject(process_info.hProcess, INFINITE); // uncomment to wait till process finish
        CloseHandle(process_info.hProcess);
        CloseHandle(process_info.hThread);
    }
    

    I strongly recommend to read this CodeProject article (A newbie's elementary guide to spawning processes).