How to tell if there is a console

2020-02-09 01:30发布

Ive 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 its a GUI app - how to tell in dll if the app has a console?

标签: c# console
10条回答
对你真心纯属浪费
2楼-- · 2020-02-09 01:39
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.

查看更多
Lonely孤独者°
3楼-- · 2020-02-09 01:39

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 a IInputReader interface for example. This way you can use the same code for multiple scenarios for getting input from the user.

查看更多
叛逆
4楼-- · 2020-02-09 01:42

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");
}
查看更多
Juvenile、少年°
5楼-- · 2020-02-09 01:53

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.

查看更多
疯言疯语
6楼-- · 2020-02-09 01:54

This SO question may provide you a solution.

Another solution is:

Console.Read() returns -1 in windows forms applications without opening up a console window. In a console app, it returns the actual value. So you can write something like:

int j = Console.Read();
if (j == -1)
    MessageBox.Show("It's not a console app");
else
    Console.WriteLine("It's a console app");

I tested this code on console and winforms apps. In a console app, if the user inputs '-1', the value of j is 45. So it will work.

查看更多
Juvenile、少年°
7楼-- · 2020-02-09 01:59

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.

查看更多
登录 后发表回答