A windows service doesn't have a GUI, so the sole notion of talking about converting a WinForms application with a GUI to a Windows service hardly makes sense. You may take a look at the following article about writing windows services using .NET. If you need to host some sevrice listening on a given port you may take a look at hosting a WCF service in a managed Windows service.
As Darin already pointed out converting a UI application into a Windows service is in most cases not a good idea.
This being said, there maybe (or are) edge cases where this can be useful.
I've so far not tried to do it with a WinForms application, but I assume that the steps are almost identical to what I once did.
I wrote a backend application, that runs as a Windows service 99.99% of the time, but can also be started as a console application for easier / faster debugging.
What you've got to do:
prevent the application from spawning multiple instances (optional; see this article on how to achieve this)
make sure your application does not rely on user interaction
upon startup of the application, check whether it is run as Windows service or in user mode
You can detect if the user started the application by querying Environment.UserInteractive - which returns false, if started as Windows service, and true when started in user mode.
your main method should then look something like this:
static void Main()
{
// do common initialization, logging framework + the likes
if (Environment.UserInteractive)
{
// start up in user mode
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new myForm());
}
else
{
// start up as Windows service
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new myService()
};
ServiceBase.Run(ServicesToRun);
}
}
A windows service doesn't have a GUI, so the sole notion of talking about converting a WinForms application with a GUI to a Windows service hardly makes sense. You may take a look at the following article about writing windows services using .NET. If you need to host some sevrice listening on a given port you may take a look at hosting a WCF service in a managed Windows service.
As Darin already pointed out converting a UI application into a Windows service is in most cases not a good idea.
This being said, there maybe (or are) edge cases where this can be useful.
I've so far not tried to do it with a WinForms application, but I assume that the steps are almost identical to what I once did.
I wrote a backend application, that runs as a Windows service 99.99% of the time, but can also be started as a console application for easier / faster debugging.
What you've got to do:
You can detect if the user started the application by querying
Environment.UserInteractive
- which returnsfalse
, if started as Windows service, andtrue
when started in user mode.your main method should then look something like this: