How to tell if there is a console

In the end I did as follows:

// Property:
private bool? _console_present;
public bool console_present {
    get {
        if (_console_present == null) {
            _console_present = true;
            try { int window_height = Console.WindowHeight; }
            catch { _console_present = false; }
        }
        return _console_present.Value;
    }
}

//Usage
if (console_present)
    Console.Read();

Following thekips advice I added a delegate member to library class to get user validation - and set this to a default implimentation that uses above to check if theres a console and if present uses that to get user validation or does nothing if not (action goes ahead without user validation). This means:

  1. All existing clients (command line apps, windows services (no user interaction), wpf apps) all work with out change.
  2. Any non console app that needs input can just replace the default delegate with someother (GUI - msg box etc) validation.

Thanks to all who replied.


You can use this code:

public static bool HasMainWindow()
{
    return (Process.GetCurrentProcess().MainWindowHandle != IntPtr.Zero);
}

Worked fine with quick test on Console vs. WinForms application.


This works for me (using native method).

First, declare:

[DllImport("kernel32.dll")]
static extern IntPtr GetConsoleWindow();

After that, check with elegance... hahaha...:

if (GetConsoleWindow() != IntPtr.Zero)
{
    Console.Write("has console");
}

if (Environment.UserInteractive)
{
    // A console is opened
}

See: http://msdn.microsoft.com/en-us/library/system.environment.userinteractive(v=vs.110).aspx

Gets a value indicating whether the current process is running in user interactive mode.

Tags:

C#

Console