How to Start a Process in Session 1 from a Windows 7 Service
12:45 19 Oct 2011

I have a service running in Windows 7. In Windows 7 all services run in Session 0. From that service I want to create an interactive user session (in a session other than Session 0) and start an application in that session. My problem is that when I call LogonUser to start an interactive user session and then use CreateProcessAsUser to start the application the application ends up running in Session 0.

All of my code is C#.

Here is the relevant code:

[DllImport("advapi32.dll", SetLastError=true)]
static extern bool LogonUser(
    string principal,
    string authority,
    string password,
    UInt32 logonType,
    UInt32 logonProvider,
    out    IntPtr token);

[DllImport("advapi32.dll", SetLastError=true)]
static extern bool CreateProcessAsUser(
    IntPtr hToken,
    string lpApplicationName,
    string lpCommandLine,
    IntPtr lpProcessAttributes,
    IntPtr lpThreadAttributes,
    bool bInheritHandles,
    int dwCreationFlags,
    IntPtr lpEnvironment,
    string lpCurrentDirectory,
    ref STARTUPINFO lpStartupInfo,
    ref PROCESS_INFORMATION lpProcessInformation);

IntPtr token;
LogonUser("UserName", ".", "Password", 
    LogonTypes.Interactive,LogonProviders.Default, out token)


string hd = Environment.ExpandEnvironmentVariables("%USERPROFILE%");

IntPtr envBlock = IntPtr.Zero;
CreateProcessAsUser(token, "PathToMenu.exe",
    NORMAL_PRIORITY_CLASS |CREATE_UNICODE_ENVIRONMENT,
    "WinSta0\\Default", hd, envBlock, "Menu");

Can anyone tell me what I'm doing wrong?

c# windows-7 service