How to tell if there is a console

前端 未结 10 2184
庸人自扰
庸人自扰 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 17:14

    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.

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

    You can pass argument on initialize.

    for example:

    In your library class, add constructor with 'IsConsole' parameter.

    public YourLibrary(bool IsConsole)
    {
      if (IsConsole)
      {
         // Do console work
      }
      else 
      {
         // Do wpf work
      }
    }
    

    And from Console you can use:

    YourLibrary lib = new YourLibrary(true);
    

    Form wpf:

    YourLibrary lib = new YourLibrary(false);
    
    0 讨论(0)
  • 2020-12-14 17:17

    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:

    1. All existing clients (command line apps, windows services (no user interaction), wpf apps) all work with out change.
    2. Any non console app that needs input can just replace the default delegate with someother (GUI - msg box etc) validation.

    Thanks to all who replied.

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

    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");
    }
    
    0 讨论(0)
提交回复
热议问题