Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to tell if there is a console

Tags:

c#

console

I've some library code that is used by both console and WPF apps. In the library code, there are some Console.Read() calls. I only want to do those input reads if the app is a console app not if it's a GUI app - how to tell in the dll if the app has a console?

like image 604
Ricibob Avatar asked Jun 20 '11 08:06

Ricibob


People also ask

What is a console c#?

A console application, in the context of C#, is an application that takes input and displays output at a command line console with access to three basic data streams: standard input, standard output and standard error.

What is the use of console?

The console is an operating system window where users interact with the operating system or with a text-based console application by entering text input through the computer keyboard, and by reading text output from the computer terminal.

How does console WriteLine work?

WriteLine(String, Object, Object) Writes the text representation of the specified objects, followed by the current line terminator, to the standard output stream using the specified format information.

What is console in VB net?

In VB.NET, Console. WriteLine prints a message to the console. And ReadLine will get user input. ReadKey() can handle key presses immediately.


2 Answers

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"); } 
like image 125
Sergio Cabral Avatar answered Sep 24 '22 05:09

Sergio Cabral


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.

like image 31
Ricibob Avatar answered Sep 22 '22 05:09

Ricibob