How to tell if there is a console

Viewed 24296

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?

11 Answers

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.

There are already a lot of (unsatisfying) answers... Here is a very simple and elegant one:

if (Console.LargestWindowWidth != 0) { /* we have a console */ }

LargestWindowWidth doesn't throw and returns 0 when there is no Console window.

(otherwise, I think it's safe to assume it will never return 0)

Related