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?
相关问题
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Why am I getting UnauthorizedAccessException on th
- 求获取指定qq 资料的方法
- How to know full paths to DLL's from .csproj f
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.
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.This works for me (using native method).
First, declare:
After that, check with elegance... hahaha...:
This is a modern (2018) answer to an old question.
The combination of
Environment.UserInteractive
andConsole.Title.Length
should give a proper answer to the question of whether there is a console window. It is a simple and straightforward solution.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: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.
You can use this code:
Worked fine with quick test on Console vs. WinForms application.