Skip to content

Instantly share code, notes, and snippets.

@fredrikhaglund
Last active January 4, 2017 12:12
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fredrikhaglund/8871209 to your computer and use it in GitHub Desktop.
Save fredrikhaglund/8871209 to your computer and use it in GitHub Desktop.
Require a Console from a non command line application (C#)
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