c# - How to be dynamically either console application or Windows Application -
i have small application should executed in two modes: non ui or wpf window. should depend on command line arguments.
in each mode, need show feedback log:
- in wpf window mode, wpf going take care of visualizing logs,
- in no ui mode, need console show logs. if app have been started console (mainly cmd.exe), i'd use without opening new one. if app have been started outside of console (double click on explorer, createprocess, ...), need create new console output results , wait readkey close it.
i have found:
- how can create new console: how open/close console window dynamically wpf application?,
- how current console windows handle show/hide it: show/hide console window of c# console application
and know can statically choose between "windows application" or "console application" in project property.
choosing "windows application", getconsolewindow() 0 , don't see how reuse previous console.
choosing "console application", can reuse previous console when started explorer in wpf window mode, console created under wpf main window.
the question is: how can application dynamic? either in wpf window mode, wpf windows (and no console @ all) or in non ui, 1 console (starting 1 or new created one).
it lot easier in winforms, not hard.
start off wpf application project (not console application project wpf windows).
create new program.cs class in root directory, add following code:
class program { [dllimport("kernel32")] public static extern void allocconsole(); [dllimport("kernel32")] public static extern void freeconsole(); [dllimport("kernel32.dll")] static extern bool attachconsole(uint dwprocessid); [stathread] public static void main(string[] args) { bool madeconsole = false; if (args.length > 0 && args[0] == "console") { if (!attachtoconsole()) { allocconsole(); console.writeline("had create console"); madeconsole = true; } console.writeline("now i'm console app!"); console.writeline("press key exit"); console.readkey(true); if (madeconsole) freeconsole(); } else { wpfapplication1.app.main(); } } public static bool attachtoconsole() { const uint parentprocess = 0xffffffff; if (!attachconsole(parentprocess)) return false; console.clear(); console.writeline("attached console!"); return true; } }
now have console app or wpf app. in properties, set start object program.main
method. in example above, wpfapplication1.app.main old start object (defined in app.xaml.cs file).
edit misses 1 of requirements using existing console , edit figure out how stay in same console window.
new edit works use existing console!
Comments
Post a Comment