How to tell if there is a console

前端 未结 10 2183
庸人自扰
庸人自扰 2020-12-14 16:34

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

相关标签:
10条回答
  • 2020-12-14 16:56
    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.

    0 讨论(0)
  • 2020-12-14 16:57

    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.

    0 讨论(0)
  • 2020-12-14 17:01

    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(); }
    
    0 讨论(0)
  • 2020-12-14 17:08

    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.

    0 讨论(0)
  • 2020-12-14 17:11

    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).

    0 讨论(0)
  • 2020-12-14 17:14

    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.

    0 讨论(0)
提交回复
热议问题