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?
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.
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.
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.
In VB.NET, Console. WriteLine prints a message to the console. And ReadLine will get user input. ReadKey() can handle key presses immediately.
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"); }
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:
Thanks to all who replied.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With