C# – How to create a Windows application that can run with a GUI *or* as a Windows service in C#

cwindows-services

I'd like to create an application using C# that…:

  • Can be run as a Windows application, with a GUI (it'll indicate progress, status, etc.)

    OR

  • Can be run as a Windows service, without a GUI

Is it possible? Can someone get me started?

I guess the alternative is that I could create a Windows service, and then a separate GUI application which can poll the Windows service to fetch data from it (progress, status, etc.).

In that case… how can I fetch data from the Windows service from my GUI application?

Best Answer

I'm doing something similar to what you're asking for. I have programmed it so that if you send the command line parameter "/form" to the executable, it will pop up a windows form instead of running as a service.

As far as running the background job itself, in both cases you will need to do some sort of threading (perhaps with a timer) to do the work and report status back to your form asynchronously. This would be a whole different discussion topic on creating threaded GUI apps.

The "form or service" code goes something like this:

static class Program
{
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    private static void Main(string[] args)
    {
        if (args.Length > 0 && args[0] == "/form")
        {
            var form = new MainForm();
            Application.Run(form);
            return;
        }

        var ServicesToRun = new ServiceBase[]
            {
                new BackgroundService()
            };

        ServiceBase.Run(ServicesToRun);
    }
}