Search code examples
c#wpfwindowsworkertopshelf

C# WPF App doesnt show form when launched by windows service created with topshelf


I have:

  1. Simple WPF app, with 1 window created by Visual studio
  2. Windows service (created with topshelf) that starts that app

If I start app manually, it appears in task manager and shows form as it should.

But when it is started by windows service, app appears in task manager, but form isnt shown. What should it the reason?

App launch code in win service

                    System.Diagnostics.Process process = new System.Diagnostics.Process();
                System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
                startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
                startInfo.FileName = _app.MainAppDirectory;
                startInfo.Arguments = "";
                process.StartInfo = startInfo;
                process.Start();

Solution

  • You can't do it. Windows services are not running under current user session. When you login to your Windows, you will get an active session including (Desktop, Environment variables, ..) and whenever you run an application (like a Simple WindowsForm or WPF, ...) it will runs under your active session. You can open up the Task manager and navigate to Detail tab to see information about the user who ran each Process (Check this for the WPF app when it's ran by your windows service).

    You can type Services on the Start menu and open up Services window and find your installed service. You can check a column named Log on As there. It's the user account who runs your Windows service (it might be Local System or Local Service).

    It's an interesting fact, you can write an application who runs even with no logged-in user.

    I had the same task, 5 years ago, I tried to steal users session. Using Impersonation you are able to steal user token and run your application as an specific user. But still you are not able to see your Application on the desktop.

    Look for a different project type to fill your requirements. maybe mark your application as an startup app and hide it's Forms from the user.