how to convert my C# winform program to service program ?
i need that my program will work like service (like listener)
how to convert my C# winform program to service program ?
i need that my program will work like service (like listener)
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 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);
}
}