To debug a windows service in visual studio I manually open a console window to leave the service running by calling console.ReadKey(true) rather than using a while(true)...
This has been working for years but recently I get an exception:
"Cannot read keys when either application does not have a console or when console input has been redirected from a file"
Projects Output Type is "Windows Application" which is the default for windows service. According to the accepted answer in Running a Windows Service in Console mode? I tried to set it to "Concole Application". The console is shown (without my ShowConsoleWindow call) but I don't know which side effects might occur if a real windows service suddenly has a console in RELEASE so I prefer to leave it as "Windows Application".
This is the startup routine
static void Main(string[] args)
{
#if (!DEBUG)
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[] { new HostService(args) };
ServiceBase.Run(ServicesToRun);
#else
InteropWindows.ShowConsoleWindow();
using (HostService srv = new HostService(args))
{
srv.MyRun(args);
Console.WriteLine("Host Service is running. Press any key to stop...");
Console.ReadKey(true);
Console.WriteLine("Stopping service...");
srv.MyStop();
}
#endif
}
InteropWindows.ShowConsoleWindow():
public static void ShowConsoleWindow()
{
var handle = NativeMethods.GetConsoleWindow();
if (handle == IntPtr.Zero)
{
bool succcess = NativeMethods.AllocConsole();
uint lastErr = NativeMethods.GetLastError();
}
else
ShowWindow(handle, ShowWindowCommand.Show);
}
NativeMethods.AllocConsole() returns true, NativeMethods.GetLastError() is 0 but the new console window does no longer open (as I said it used to work for years).
Console.WriteLine() does not print anything, but does not throw either.
Console.ReadKey(true); in Main program then throws the exception shown above.
Following the exception's advise to use Console.Read() instead, just blocks the application infinitly so I could just use while(true);
Any ideas?