-1
    STARTUPINFO si = {sizeof(STARTUPINFO)};
    PROCESS_INFORMATION pi;
    si.cb = sizeof(STARTUPINFO);

    printf("CreateProcess(n): %x\nGLE: %x\n", CreateProcess(L"C:\\Windows\\System32\\osk.exe", NULL, 0, 0, false, NULL, 0, 0, &si, &pi), GetLastError());

Prints CreateProcess(n): 0\nGLE: 0 and no program is started. Whereas, when I replace the file location with C:\\Windows\\Notepad.exe, notepad launches. (x64 project executing on x64 Windows 10).

  • 6
    Don't rely on the order of evaluation of function arguments. It's entirely possible that `GetLastError` is called first and it makes the code harder to read embedding both of those inside a `printf` call anyway. – chris Mar 08 '21 at 21:56
  • 2
    @chris "*Don't rely on the order of evaluation of function arguments*" - IIRC, modern C++ actually corrects that so the order of evaluation will do the right thing as expected. But yes, this code is not a good approach. `CreateProcess()` and `GetLastError()` should be called separately and the results saved to variables, and then the variables passed to `printf()`. – Remy Lebeau Mar 08 '21 at 22:00
  • 1
    Unrelated: The line `si.cb = sizeof(STARTUPINFO);` looks unnecessary since you've already set `cb` in the initialization. – Ted Lyngmo Mar 08 '21 at 22:00
  • 3
    @RemyLebeau, They're sequenced now so `f(i++, i++)` is "okay", but the order is still up to the compiler. – chris Mar 08 '21 at 22:01
  • 4
    `GetLastError` called **before** `CreateProcess` in your case. if call it in correct time - `ERROR_ELEVATION_REQUIRED` - *The requested operation requires elevation.* will be. – RbMm Mar 08 '21 at 22:07
  • @rem [What are the evaluation order guarantees introduced by C++17?](https://stackoverflow.com/q/38501587/1889329) – IInspectable Mar 09 '21 at 03:09

1 Answers1

0

As the comment said, because GetLastError is called before CreateProcess, the error code you receive is 0.

If you call it correctly, it will return the error ERROR_ELEVATION_REQUIRED:

    STARTUPINFO si = { sizeof(STARTUPINFO) };
    PROCESS_INFORMATION pi;
    si.cb = sizeof(STARTUPINFO);
    CreateProcess(L"C:\\Windows\\System32\\osk.exe", NULL, 0, 0, false, NULL, 0, 0, &si, &pi);
    int e = GetLastError();
    printf("%d\n", e);

enter image description here

Using ShellExecute is recommended by Microsoft: Using the ElevateCreateProcess Fix:

ShellExecute(NULL, L"open", L"C:\\Windows\\System32\\osk.exe", NULL, NULL, SW_SHOWNORMAL);
Song Zhu
  • 3,265
  • 3
  • 5
  • 15