locked
How to open console window in Windows Apllication

    Question

  • Hi, sorry for english.

    I'm beginer in C#.

    I wrote a simple C# Windows application. Now I want to redirect all standart output to console window.
    So, I must create it and then to set as standart output handler.

    When I programmed in C++, I did this at begining of application like next:
    ...
    AllocConsole(); 
    stdout->_file=_open_osfhandle((intptr_t)GetStdHandle(STD_OUTPUT_HANDLE),0);
    ...
    printf("Hello world!");

    How to do this in C#?
    I need something like next:
    ...
    // Here I need opening console window
    ...
    Console.WriteLine("Hello World!"); // this must be written in console window.
    Thursday, August 14, 2008 8:45 AM

Answers

  • Here is full example of C# windows application with console window

    using System;  
    using System.Windows.Forms;  
    using System.Text;  
    using System.IO;  
    using System.Runtime.InteropServices;  
    using Microsoft.Win32.SafeHandles;  
     
    namespace WindowsApplication  
    {  
        static class Program  
        {  
            [DllImport("kernel32.dll",  
                EntryPoint = "GetStdHandle",  
                SetLastError = true,  
                CharSet = CharSet.Auto,  
                CallingConvention = CallingConvention.StdCall)]  
            private static extern IntPtr GetStdHandle(int nStdHandle);  
            [DllImport("kernel32.dll",  
                EntryPoint = "AllocConsole",  
                SetLastError = true,  
                CharSet = CharSet.Auto,  
                CallingConvention = CallingConvention.StdCall)]  
            private static extern int AllocConsole();  
            private const int STD_OUTPUT_HANDLE = -11;  
            private const int MY_CODE_PAGE = 437;  
     
            static void Main(string[] args)  
            {  
                Console.WriteLine("This text you can see in debug output window.");  
                  
                AllocConsole();  
                IntPtr stdHandle=GetStdHandle(STD_OUTPUT_HANDLE);  
                SafeFileHandle safeFileHandle = new SafeFileHandle(stdHandle, true);  
                FileStream fileStream = new FileStream(safeFileHandle, FileAccess.Write);  
                Encoding encoding = System.Text.Encoding.GetEncoding(MY_CODE_PAGE);  
                StreamWriter standardOutput = new StreamWriter(fileStream, encoding);  
                standardOutput.AutoFlush = true;  
                Console.SetOut(standardOutput);  
     
                Console.WriteLine("This text you can see in console window.");  
     
                MessageBox.Show("Now I'm happy!");  
            }  
        }  
    • Marked as answer by Dmitri567 Thursday, August 14, 2008 2:10 PM
    Thursday, August 14, 2008 2:06 PM

All replies

  • Hi,

    I do not understand why you need a console output in case of windows application.
    anywayz, following code may be helpful to you to open and create a command window from the windows application.

    Process commandProcess = new Process();
    commandProcess.StartInfo.FileName =
    "cmd";
    commandProcess.Start();

    Process and ProcessStartInfo belongs to System.Diagnostics namespace, you can set the properties of Process class as per your requirement.

    Hope this helps,
    Kiran Kotra

    Thursday, August 14, 2008 9:14 AM
  •  I need it for some my debug outputs.

    Look what I discovered:

    using System.Runtime.InteropServices;
    ...
    [
    DllImport("kernel32.dll", EntryPoint = "AllocConsole", SetLastError = true, CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
    private static extern int AllocConsole();
    ...
    // very very begining of application
    AllocConsole();
    Console.WriteLine("Hello World!"); // outputs to console window

    Only one trouble: AllocConsole must be before any console outputs or all outputs would be placed to standart "hidden" stream.

    May be more C# freindly method exists? (DllImport, kernel32.dll looks bad in C#).

    • Edited by Dmitri567 Thursday, August 14, 2008 11:45 AM update
    Thursday, August 14, 2008 11:39 AM
  • Here is full example of C# windows application with console window

    using System;  
    using System.Windows.Forms;  
    using System.Text;  
    using System.IO;  
    using System.Runtime.InteropServices;  
    using Microsoft.Win32.SafeHandles;  
     
    namespace WindowsApplication  
    {  
        static class Program  
        {  
            [DllImport("kernel32.dll",  
                EntryPoint = "GetStdHandle",  
                SetLastError = true,  
                CharSet = CharSet.Auto,  
                CallingConvention = CallingConvention.StdCall)]  
            private static extern IntPtr GetStdHandle(int nStdHandle);  
            [DllImport("kernel32.dll",  
                EntryPoint = "AllocConsole",  
                SetLastError = true,  
                CharSet = CharSet.Auto,  
                CallingConvention = CallingConvention.StdCall)]  
            private static extern int AllocConsole();  
            private const int STD_OUTPUT_HANDLE = -11;  
            private const int MY_CODE_PAGE = 437;  
     
            static void Main(string[] args)  
            {  
                Console.WriteLine("This text you can see in debug output window.");  
                  
                AllocConsole();  
                IntPtr stdHandle=GetStdHandle(STD_OUTPUT_HANDLE);  
                SafeFileHandle safeFileHandle = new SafeFileHandle(stdHandle, true);  
                FileStream fileStream = new FileStream(safeFileHandle, FileAccess.Write);  
                Encoding encoding = System.Text.Encoding.GetEncoding(MY_CODE_PAGE);  
                StreamWriter standardOutput = new StreamWriter(fileStream, encoding);  
                standardOutput.AutoFlush = true;  
                Console.SetOut(standardOutput);  
     
                Console.WriteLine("This text you can see in console window.");  
     
                MessageBox.Show("Now I'm happy!");  
            }  
        }  
    • Marked as answer by Dmitri567 Thursday, August 14, 2008 2:10 PM
    Thursday, August 14, 2008 2:06 PM
  • Just setting C# project output type to console application will work too.

    Friday, March 13, 2009 8:30 AM
  • Ok, I am "very" new to C# programming, tried the example above, because I too need to run some stuff in a command window, dont ask, it's complicated, anyways...

    I can now open the console window, write to it... but....

    How can I kill it, or terminate  the window when I have finished with it?

    Thanks.
    Tuesday, April 07, 2009 8:33 PM
  • [DllImport("kernel32.dll", EntryPoint = "FreeConsole", SetLastError = true, CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
    public static extern int FreeConsole();
    Here you go. You want to know how I found it? Went to a search engine, searched "winapi reference", since it's all Windows api commands, and went to the Console category of the Winapi stuff (it was a MS site ;) ). And there I found this: http://msdn.microsoft.com/en-us/library/ms683150(VS.85).aspx
    Wednesday, April 15, 2009 10:42 AM
  • Hi, Dmitri567:
         The code below just show how to do similar things in a WinForm application.

    using System;
    using System.IO;
    using System.Windows.Forms;
    
    namespace WinFromOutputToConsoleOrFile
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
            
            //Allocate a Console and I/O with it.
            private void btn_to_console_Click(object sender, EventArgs e)
            {
                if (NativeMethods.AllocConsole())
                {
                    lbl_console_alloc_result.Text = "Console allocation successfully!";
                    IntPtr stdHandle = NativeMethods.GetStdHandle(NativeMethods.STD_OUTPUT_HANDLE);
                    Console.WriteLine("from WinForm to Console!");
                    lbl_console_alloc_result.Text = Console.ReadLine();
                }
                else
                    lbl_console_alloc_result.Text = "Console allocation failed!";
            }
    
            //Redirect the StdOut to file and write file through it.
            private void btn_to_file_Click(object sender, EventArgs e)
            {
                FileStream fs = File.Open(@"e:\from_win_form.txt", FileMode.OpenOrCreate);
                StreamWriter sw = new StreamWriter(fs);
                Console.SetOut(sw);
                Console.WriteLine("from WinForm to File!");
                sw.Close();
                fs.Close();
            }
        }
    
        public partial class NativeMethods
        {
            public static Int32 STD_OUTPUT_HANDLE = -11;
    
            /// Return Type: HANDLE->void*
            ///nStdHandle: DWORD->unsigned int
            [System.Runtime.InteropServices.DllImportAttribute("kernel32.dll", EntryPoint = "GetStdHandle")]
            public static extern System.IntPtr GetStdHandle(Int32 nStdHandle);
    
            /// Return Type: BOOL->int
            [System.Runtime.InteropServices.DllImportAttribute("kernel32.dll", EntryPoint = "AllocConsole")]
            [return: System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.Bool)]
            public static extern bool AllocConsole();
        }
    }
    



    Please mark the right answer at right time.
    Thanks,
    Sam
    • Edited by SamAgain Saturday, February 27, 2010 4:55 PM refine
    Saturday, February 27, 2010 4:52 PM