Skip to content

Commit

Permalink
adds a protection that prevents the process from crashing when runnin…
Browse files Browse the repository at this point in the history
…g in windowless mode
  • Loading branch information
Pedro Salgueiro authored and phatboyg committed Jan 13, 2020
1 parent 60a995d commit 7638586
Showing 1 changed file with 25 additions and 2 deletions.
27 changes: 25 additions & 2 deletions src/Topshelf/Hosts/ConsoleRunHost.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@ namespace Topshelf.Hosts
using System;
using System.Diagnostics;
using System.IO;
#if !NETCORE
using System.Runtime.InteropServices;
#endif
using System.Threading;
using System.Threading.Tasks;
using Logging;
Expand All @@ -28,6 +31,11 @@ public class ConsoleRunHost :
Host,
HostControl
{

#if !NETCORE
[DllImport("kernel32.dll")]
static extern IntPtr GetConsoleWindow();
#endif
readonly LogWriter _log = HostLogger.Get<ConsoleRunHost>();
readonly HostEnvironment _environment;
readonly ServiceHandle _serviceHandle;
Expand Down Expand Up @@ -94,8 +102,23 @@ public TopshelfExitCode Run()

_exit = new ManualResetEvent(false);
_exitCode = TopshelfExitCode.Ok;

Console.Title = _settings.DisplayName;
#if !NETCORE
if(GetConsoleWindow() != IntPtr.Zero)
{
try
{
// It is common to run console applications in windowless mode, this prevents
// the process from crashing when attempting to set the title.
#endif
Console.Title = _settings.DisplayName;
#if !NETCORE
}
catch(IOException e)
{
_log.Info("It was not possible to set the console window title. See the inner exception for details.", e);
}
}
#endif
Console.CancelKeyPress += HandleCancelKeyPress;

if (!_serviceHandle.Start(this))
Expand Down

0 comments on commit 7638586

Please sign in to comment.