Search code examples
winformswindows-servicestopshelf

Windows Service can not open Windows Form


I am trying to create a Windows Service using TopShelf and within this service i want to launch a Windows Form.After i created the service and i debugged it calling ShowDialog the form does not show up:

Service

 class SimpleServ {
    private Task task;
    private const string PATH = @"D:/out.txt";
    private Logger logger;
    private CancellationTokenSource src = new CancellationTokenSource();
    public SimpleServ() {
        logger = new Logger();

    }
    public void Start() {

        logger.Log("Started");
        this.task = Task.Run(async () => {

            var fm = new Fm(logger);
            while (true) {
                fm.ShowDialog();
                logger.Log("Just closed the dialog");
                await Task.Delay(3000);
            }
        });
    }
    public void Stop() {
        logger.Log("Stopped service");
    }
}

Form

public partial class Fm : Form {
    private Logger log;
    public Fm(Logger log) {
        this.log = log;
        this.log.Log("From Form constructor");
        InitializeComponent();

    }

    private void button1_Click(object sender, EventArgs e) {
        this.log.Log("Button clicked");
        this.Close();
    }
}

Main

class Program {
        static void Main(string[] args) {
            var exitCode = HostFactory.Run(x => {
                x.Service<SimpleServ>(s => {
                    s.ConstructUsing(h => new SimpleServ());
                    s.WhenStarted(h => h.Start());
                    s.WhenStopped(h => h.Stop());
                });
                x.RunAsLocalSystem();
                x.SetServiceName("SimpleService");
                x.SetDisplayName("Simple Service");
                x.SetDescription("Simple serv description");

            });
            int exitCodeValue = (int)Convert.ChangeType(exitCode, exitCode.GetTypeCode());
            Environment.ExitCode = exitCodeValue;
        }
    }

I have attached myself to the service and after it reaches the line of ShowDialog nothing happens.

Update
I have also added a Logger to log all important events and so far , it seems the form opens but i can not see it:

Logger

public class Logger {
        private string path;
        public Logger(string logPath=Constants.PATH) {
            this.path = logPath;
        }
        private object @lock = new object();
        public void Log(string message) {
            string formattedMessage = "Date:" + DateTime.Now.ToString() + "\tMessage:" + message;
            File.AppendAllLines(this.path, new string[] { formattedMessage });
        }
    }

The output of the file is :

Date:6/12/2019 11:19:13 AM  Message:Started
Date:6/12/2019 11:19:13 AM  Message:From Form constructor

Solution

  • In a world where Session 0 Isolation -- an important security measure to prevent Shatter attacks -- is the law of the land, you should think very carefully about any design relying on service interaction.

    A best practice is to restructure your solution to have:

    1. A service that runs in the background, independently of the user
    2. A conventional GUI application that interacts with the service and can be run by any user