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:59

if you want a good design, abstract the GUI dependences using an interface. Implements 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).

查看更多
乱世女痞
3楼-- · 2020-02-09 01:59

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()) { Console.Read(); }
查看更多
smile是对你的礼貌
4楼-- · 2020-02-09 02:00

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.

查看更多
5楼-- · 2020-02-09 02:02

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);
查看更多
登录 后发表回答