Console in Windows application
Sometimes it is convenient to have a text console in windows non-console application. For example it is much more convenient to debug windows service in console than as a real service.
If you try to do Console.WriteLine() from our service, it will produce nothing, because there is no console window at all. You can go to project settings and change project type from windows application to console application, but it is inconvenient, because your will have to remember to undo it.
Initialize console in windows application is easy calling API function:
[System.Runtime.InteropServices.DllImport("kernel32")]
static extern bool AllocConsole();
Now you can add some parameter parsing and programmatically switch into console mode without tweaking your project.
Another nice trick is to switch into console mode instead of windows service mode whenever you run your project under Visual Studio debugger.
static class Program
{
static void Main()
{
if (AppDomain.CurrentDomain.DomainManager.GetType().Name !=
"VSHostAppDomainManager")
{
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[] { new Service1() };
ServiceBase.Run(ServicesToRun);
}
else
{
AllocConsole();
var srv = new Service1();
srv.Start();
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
srv.Stop();
}
}
[System.Runtime.InteropServices.DllImport("kernel32")]
static extern bool AllocConsole();
}