Is it possible to log message from WinForms app to cmd.exe process started programmatically? I\'ve tried to do all kinds of variations of following code:
pri
You're in luck. I just solved this for a code generator toy project I had floating around here.
Using AttachConsole
or AllocConsole
Win32 API's you can achieve the result, by just using System.Console.WriteLine
(or Read, or Error.WriteLine etc) like you normally would.
The following snippet figures out when a forms app was started from a Console window, and attaches to it's parent console; If that doesn't work, it will create it's own console, and remember to keep it open (so it doesn't vanish before the user can read the output, for example).
[DllImport("kernel32.dll")] static extern bool AllocConsole();
[DllImport("kernel32.dll")] static extern bool AttachConsole(int pw);
private static bool _hasConsole, _keepConsoleOpen;
static private void EnsureConsole()
{
_hasConsole = _hasConsole || AttachConsole(-1);
_keepConsoleOpen = !_hasConsole || _keepConsoleOpen;
_hasConsole = _hasConsole || AllocConsole();
}
[STAThread]
private static void Main(string[] args)
{
EnsureConsole();
// the usual stuff -- your program
if (_keepConsoleOpen)
{
Console.WriteLine("(press enter)...");
Console.Read();
}
}