Last active
January 4, 2017 12:12
-
-
Save fredrikhaglund/8871209 to your computer and use it in GitHub Desktop.
Require a Console from a non command line application (C#)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Runtime.InteropServices; | |
using System.Text; | |
namespace Launcher | |
{ | |
class ConsoleHelper | |
{ | |
[DllImport("kernel32.dll")] | |
private static extern bool AllocConsole(); | |
[DllImport("kernel32.dll")] | |
private static extern bool AttachConsole(int pid); | |
private static bool _consoleAttached; | |
public static void RequireConsole() | |
{ | |
if (_consoleAttached) return; | |
if (!AttachConsole(-1)) // Attach to an parent process console | |
{ | |
AllocConsole(); // Alloc a new console if not present | |
} | |
_consoleAttached = true; | |
} | |
internal static void AbortWithMessage(string message) | |
{ | |
RequireConsole(); | |
Console.WriteLine(message); | |
Environment.Exit(1); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment