module Process

def create_process_as_user(token, app, cmd, process_security, thread_security, inherit, creation_flags, env, cwd, startinfo, procinfo)

def create_process_as_user(token, app, cmd, process_security, thread_security, inherit, creation_flags, env, cwd, startinfo, procinfo)
  bool = CreateProcessAsUserW(
    token,                  # User token handle
    app,                    # App name
    cmd,                    # Command line
    process_security,       # Process attributes
    thread_security,        # Thread attributes
    inherit,                # Inherit handles
    creation_flags,         # Creation Flags
    env,                    # Environment
    cwd,                    # Working directory
    startinfo,              # Startup Info
    procinfo                # Process Info
  )
  unless bool
    if FFI.errno == ERROR_PRIVILEGE_NOT_HELD
      raise SystemCallError.new("CreateProcessAsUserW (User '#{::ENV['USERNAME']}' must hold the 'Replace a process level token' and 'Adjust Memory Quotas for a process' permissions. Logoff the user after adding this right to make it effective.)", FFI.errno)
    else
      raise SystemCallError.new("CreateProcessAsUserW failed.", FFI.errno)
    end
  end
ensure
  CloseHandle(token)
end