Run Application from Service, CreateProcessAsUser Fails

I know! I shouldn't run a GUI application from a Windows service, but this is what I should accomplish as a requirement. Putting different codes from around the Web together, I have the following procedure. I see Access Violation error in log, as a result of CreateProcessAsUser. I have tries different settings with no luck. Any idea what is wrong with this code?

procedure TMyService.RunApp;
  SessionID: DWORD;
  UserToken: THandle;
  CmdLine: PChar;
  SessionId:= WtsGetActiveConsoleSessionID;
  if SessionID = $FFFFFFFF then Exit;
  if WTSQueryUserToken(SessionID, UserToken) then begin
    CmdLine:= 'notepad.exe';
    ZeroMemory(@si, SizeOf(si));
    si.cb := SizeOf(si);
    SI.lpDesktop := PChar('winsta0\Default');
    SI.wShowWindow := SW_SHOWNORMAL;
    ZeroMemory(@pi, SizeOf(pi));
      CreateProcessAsUser(UserToken, nil, CmdLine, nil, nil, False,
      0, nil, nil, si, pi);
    except on E: Exception do
      // Log exception ...
  end else begin
    // Log GetLastError ...

BTW, WTSQueryUserToken is used from JEDI API Library and is defined as:

function WTSQueryUserToken(SessionId: ULONG; var phToken: THandle): BOOL; stdcall;


The third parameter must be a pointer to a modifiable string, as documented on MSDN:

The Unicode version of this function, CreateProcessAsUserW, can modify the contents of this string. Therefore, this parameter cannot be a pointer to read-only memory (such as a const variable or a literal string). If this parameter is a constant string, the function may cause an access violation.

A string literal is stored in read only memory. Try this instead:

  CmdLine: string;
CmdLine := 'notepad.exe';
UniqueString(CmdLine); // make modifiable;
if not CreateProcessAsUser(..., PChar(CmdLine), ...) then
  // handle error

Need Your Help

Using $_POST in mySQL query

php mysql sql forms post

I am trying to create a program where the user will enter a state abbreviation in a form field and the output will be colleges that are in that state. Here is my code: