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 rea
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.
This is a modern (2018) answer to an old question.
var isReallyAConsoleWindow = Environment.UserInteractive && Console.Title.Length > 0;
The combination of Environment.UserInteractive
and Console.Title.Length
should give a proper answer to the question of whether there is a console window.
It is a simple and straightforward solution.
I rewrote @Ricibob's answer
public bool console_present {
get {
try { return Console.WindowHeight > 0; }
catch { return false; }
}
}
//Usage
if (console_present) { Console.Read(); }
It is simpler, but I prefer this native implementation:
[DllImport("kernel32.dll")]
static extern IntPtr GetConsoleWindow();
//Usage
if (GetConsoleWindow() != IntPtr.Zero) { Console.Read(); }
You should fix this in your design. This is a nice example of a place in which inversion of control would be very handy. As the calling code is aware of which UI is available, this code should specify an instance of an IInputReader
interface, for example. This way, you can use the same code for multiple scenarios for getting input from the user.
If you want a good design, abstract the GUI dependences using an interface.
Implement a concrete class for the console version, another for the WPF version, and inject the correct version using any way (dependency injection, inversion of control, etc).
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.