添加链接
link之家
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

Is there a way to show the console in a Windows application?

I want to do something like this:

static class Program
    [STAThread]
    static void Main(string[] args) {
        bool consoleMode = Boolean.Parse(args[0]);
        if (consoleMode) {
            Console.WriteLine("consolemode started");
            // ...
        } else {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());

What you want to do is not possible in a sane way. There was a similar question so look at the answers.

Then there's also an insane approach (site down - backup available here.) written by Jeffrey Knight:

Question: How do I create an application that can run in either GUI (windows) mode or command line / console mode?

On the surface of it, this would seem easy: you create a Console application, add a windows form to it, and you're off and running. However, there's a problem:

Problem: If you run in GUI mode, you end up with both a window and a pesky console lurking in the background, and you don't have any way to hide it.

What people seem to want is a true amphibian application that can run smoothly in either mode.

If you break it down, there are actually four use cases here:

User starts application from existing cmd window, and runs in GUI mode
User double clicks to start application, and runs in GUI mode
User starts application from existing cmd window, and runs in command mode
User double clicks to start application, and runs in command mode.
  

I'm posting the code to do this, but with a caveat.

I actually think this sort of approach will run you into a lot more trouble down the road than it's worth. For example, you'll have to have two different UIs' -- one for the GUI and one for the command / shell. You're going to have to build some strange central logic engine that abstracts from GUI vs. command line, and it's just going to get weird. If it were me, I'd step back and think about how this will be used in practice, and whether this sort of mode-switching is worth the work. Thus, unless some special case called for it, I wouldn't use this code myself, because as soon as I run into situations where I need API calls to get something done, I tend to stop and ask myself "am I overcomplicating things?".

Output type=Windows Application

using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Diagnostics;
using Microsoft.Win32;
namespace WindowsApplication
    static class Program
    DEMO CODE ONLY: In general, this approach calls for re-thinking 
    your architecture!
    There are 4 possible ways this can run:
    1) User starts application from existing cmd window, and runs in GUI mode
    2) User double clicks to start application, and runs in GUI mode
    3) User starts applicaiton from existing cmd window, and runs in command mode
    4) User double clicks to start application, and runs in command mode.
    To run in console mode, start a cmd shell and enter:
        c:\path\to\Debug\dir\WindowsApplication.exe console
        To run in gui mode,  EITHER just double click the exe, OR start it from the cmd prompt with:
        c:\path\to\Debug\dir\WindowsApplication.exe (or pass the "gui" argument).
        To start in command mode from a double click, change the default below to "console".
    In practice, I'm not even sure how the console vs gui mode distinction would be made from a
    double click...
        string mode = args.Length > 0 ? args[0] : "console"; //default to console
        [DllImport("kernel32.dll", SetLastError = true)]
        static extern bool AllocConsole();
        [DllImport("kernel32.dll", SetLastError = true)]
        static extern bool FreeConsole();
        [DllImport("kernel32", SetLastError = true)]
        static extern bool AttachConsole(int dwProcessId);
        [DllImport("user32.dll")]
        static extern IntPtr GetForegroundWindow();
        [DllImport("user32.dll", SetLastError = true)]
        static extern uint GetWindowThreadProcessId(IntPtr hWnd, out int lpdwProcessId);
        [STAThread]
        static void Main(string[] args)
            //TODO: better handling of command args, (handle help (--help /?) etc.)
            string mode = args.Length > 0 ? args[0] : "gui"; //default to gui
            if (mode == "gui")
                MessageBox.Show("Welcome to GUI mode");
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new Form1());
            else if (mode == "console")
                //Get a pointer to the forground window.  The idea here is that
                //IF the user is starting our application from an existing console
                //shell, that shell will be the uppermost window.  We'll get it
                //and attach to it
                IntPtr ptr = GetForegroundWindow();
                int  u;
                GetWindowThreadProcessId(ptr, out u);
                Process process = Process.GetProcessById(u);
                if (process.ProcessName == "cmd" )    //Is the uppermost window a cmd process?
                    AttachConsole(process.Id);
                    //we have a console to attach to ..
                    Console.WriteLine("hello. It looks like you started me from an existing console.");
                    //no console AND we're in console mode ... create a new console.
                    AllocConsole();
                    Console.WriteLine(@"hello. It looks like you double clicked me to start
                   AND you want console mode.  Here's a new console.");
                    Console.WriteLine("press any key to continue ...");
                    Console.ReadLine();       
                FreeConsole();
                I find it ironic with Microsoft and how it wants to create C# interfaces for all of it's API, yet there is no C# way to perform such a simple task.
– Ramon Zarazua B.
                Apr 17, 2011 at 8:57
                Rather than depending on console being the foreground window, you could get parent process id of current process using winapi: stackoverflow.com/a/3346055/855432
– ghord
                Sep 11, 2012 at 8:06
                As of the time of writing, backup copy of the article is available here web.archive.org/web/20111227234507/http://www.rootsilver.com/…
– Andrew Savinykh
                Apr 18, 2013 at 2:19
                Hi! I found that if I ran this solution from shell like Far, nc    it creates new console. If I attache to Far Console like cmd it works wrong. I recommend to create ConsoleApplication and if GUI needed then do FreeConsole(); Excellent article! Thanks!
– Maxim Vasiliev
                May 16, 2013 at 9:44
                I'd recommend calling AttachConsole with -1 (the value of the API constant ATTACH_PARENT_PROCESS) rather than hoping the foreground window is the right command window to write to.
– Jon Hanna
                Nov 15, 2013 at 17:04

This is a tad old (OK, it's VERY old), but I'm doing the exact same thing right now. Here's a very simple solution that's working for me:

[DllImport("kernel32.dll", SetLastError = true)]
static extern bool AllocConsole();
[DllImport("kernel32.dll")]
static extern IntPtr GetConsoleWindow();
[DllImport("user32.dll")]
static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
const int SW_HIDE = 0;
const int SW_SHOW = 5;
public static void ShowConsoleWindow()
    var handle = GetConsoleWindow();
    if (handle == IntPtr.Zero)
        AllocConsole();
        ShowWindow(handle, SW_SHOW);
public static void HideConsoleWindow()
    var handle = GetConsoleWindow();
    ShowWindow(handle, SW_HIDE);
                if you are running this in a cmd window, this will open another console window which is not desirable in automated process that will need to capture console output.
– AaA
                Jan 8, 2015 at 3:07
                On my end, I used the code provided but added a InitConsole() shared function to do the AllocConsole() part if handle is intptr.zero.   When I used ShowConsoleWindow then printed on it immediately after, it didn't work. Allocating the console when application starts then using the ShowConsoleWindow did works. Other than that, this is perfect for me. Thank you..
– Sage Pourpre
                Apr 11, 2016 at 2:34

Disclaimer

There is a way to achieve this which is quite simple, but I wouldn't suggest it is a good approach for an app you are going to let other people see. But if you had some developer need to show the console and windows forms at the same time, it can be done quite easily.

This method also supports showing only the Console window, but does not support showing only the Windows Form - i.e. the Console will always be shown. You can only interact (i.e. receive data - Console.ReadLine(), Console.Read()) with the console window if you do not show the windows forms; output to Console - Console.WriteLine() - works in both modes.

This is provided as is; no guarantees this won't do something horrible later on, but it does work.

Project steps

Start from a standard Console Application.

Mark the Main method as [STAThread]

Add a reference in your project to System.Windows.Forms

Add a Windows Form to your project.

Add the standard Windows start code to your Main method:

End Result

You will have an application that shows the Console and optionally windows forms.

Sample Code

Program.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace ConsoleApplication9 {
    class Program {
        [STAThread]
        static void Main(string[] args) {
            if (args.Length > 0 && args[0] == "console") {
                Console.WriteLine("Hello world!");
                Console.ReadLine();
            else {
                Application.EnableVisualStyles(); 
                Application.SetCompatibleTextRenderingDefault(false); 
                Application.Run(new Form1());

Form1.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace ConsoleApplication9 {
    public partial class Form1 : Form {
        public Form1() {
            InitializeComponent();
        private void Form1_Click(object sender, EventArgs e) {
            Console.WriteLine("Clicked");
                nice code here.  but how do you disable showing the console if you want to sell or deploy or something else.???
– r4ccoon
                Sep 20, 2009 at 21:50
                Well, IMHO a simpler way to achieve the same effect is to create a Windows Forms Project as usual, then right click it in the Solution Explorer -> Properties, and change Output Type to Console Application. (edit: now I've realised it's basically ICR's answer)
– kamilk
                Jan 2, 2013 at 11:22

Resurrecting a very old thread yet again, since none of the answers here worked very well for me.

I found a simple way that seems pretty robust and simple. It worked for me. The idea:

  • Compile your project as a Windows Application. There might be a parent console when your executable starts, but maybe not. The goal is to re-use the existing console if one exists, or create a new one if not.
  • AttachConsole(-1) will look for the console of the parent process. If there is one, it attaches to it and you're finished. (I tried this and it worked properly when calling my application from cmd)
  • If AttachConsole returned false, there is no parent console. Create one with AllocConsole.
  • Example:

    static class Program
        [DllImport( "kernel32.dll", SetLastError = true )]
        static extern bool AllocConsole();
        [DllImport( "kernel32", SetLastError = true )]
        static extern bool AttachConsole( int dwProcessId );
        static void Main(string[] args)
            bool consoleMode = Boolean.Parse(args[0]);
            if (consoleMode)
               if (!AttachConsole(-1))
                  AllocConsole();
               Console.WriteLine("consolemode started");
               // ...
               Application.EnableVisualStyles();
               Application.SetCompatibleTextRenderingDefault(false);
               Application.Run(new Form1());
    

    A word of caution : it seems that if you try writing to the console prior to attaching or allocing a console, this approach doesn't work. My guess is the first time you call Console.Write/WriteLine, if there isn't already a console then Windows automatically creates a hidden console somewhere for you. (So perhaps Anthony's ShowConsoleWindow answer is better after you've already written to the console, and my answer is better if you've not yet written to the console). The important thing to note is that this doesn't work:

    static void Main(string[] args)
            Console.WriteLine("Welcome to the program");   //< this ruins everything
            bool consoleMode = Boolean.Parse(args[0]);
            if (consoleMode)
               if (!AttachConsole(-1))
                  AllocConsole();
               Console.WriteLine("consolemode started");   //< this doesn't get displayed on the parent console
               // ...
               Application.EnableVisualStyles();
               Application.SetCompatibleTextRenderingDefault(false);
               Application.Run(new Form1());
                    thank you for sharing sample code. I've tried it and found that it works but with limitations. There is no console output redirection (can be fixed by additional source code). But the main disadvantage is that it returns control immediately to the console. For example when i type \bin\Debug>shareCheck.exe /once  and press Enter command prompt is shown and then console starts to output: \bin\Debug>hello. It looks like you started me from an existing console. and when program ends there is no command prompt so last output line and blank screen that is a little bit crazy
    – oleksa
                    Oct 17, 2017 at 9:43
                    Thanks Kevin for the word of caution - I am having trouble with the approaches suggested in this SO post and I seem to be getting the "hidden console" even though I don't have any Console output happening before...  It turned out that the "Output" window in Visual Studio is the hidden console, if your app is running with Debugger attached! Worth mentioning... (so, my program worked when switching to run without debugger, i.e. Ctrl-F5)
    – Per Lundberg
                    Aug 4, 2018 at 20:12
            #region DllImport
            [DllImport("kernel32.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall, SetLastError = true)]
            [return: MarshalAs(UnmanagedType.Bool)]
            private static extern bool AllocConsole();
            [DllImport("kernel32.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall, SetLastError = true)]
            [return: MarshalAs(UnmanagedType.Bool)]
            private static extern bool CloseHandle(IntPtr handle);
            [DllImport("kernel32.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall, SetLastError = true)]
            private static extern IntPtr CreateFile([MarshalAs(UnmanagedType.LPStr)]string fileName, [MarshalAs(UnmanagedType.I4)]int desiredAccess, [MarshalAs(UnmanagedType.I4)]int shareMode, IntPtr securityAttributes, [MarshalAs(UnmanagedType.I4)]int creationDisposition, [MarshalAs(UnmanagedType.I4)]int flagsAndAttributes, IntPtr templateFile);
            [DllImport("kernel32.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall, SetLastError = true)]
            [return: MarshalAs(UnmanagedType.Bool)]
            private static extern bool FreeConsole();
            [DllImport("kernel32.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall, SetLastError = true)]
            private static extern IntPtr GetStdHandle([MarshalAs(UnmanagedType.I4)]int nStdHandle);
            [DllImport("kernel32.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall, SetLastError = true)]
            [return: MarshalAs(UnmanagedType.Bool)]
            private static extern bool SetStdHandle(int nStdHandle, IntPtr handle);
            #endregion
            #region Methods
            public static void Create()
                var ptr = GetStdHandle(-11);
                if (!AllocConsole())
                    throw new Win32Exception("AllocConsole");
                ptr = CreateFile("CONOUT$", 0x40000000, 2, IntPtr.Zero, 3, 0, IntPtr.Zero);
                if (!SetStdHandle(-11, ptr))
                    throw new Win32Exception("SetStdHandle");
                var newOut = new StreamWriter(Console.OpenStandardOutput());
                newOut.AutoFlush = true;
                Console.SetOut(newOut);
                Console.SetError(newOut);
            public static void Hide()
                var ptr = GetStdHandle(-11);
                if (!CloseHandle(ptr))
                    throw new Win32Exception();
                ptr = IntPtr.Zero;
                if (!FreeConsole())
                    throw new Win32Exception();
            #endregion
    

    As per Jeffrey Knight quote above, as soon as I run into situations where I need API calls to get something done, I tend to stop and ask myself "am I overcomplicating things?".

    If what is wanted is to have some code and run it in Windows GUI mode or Console mode, consider moving the code used in both modes off to a code library DLL, and then having a Windows Forms application that uses that DLL, and a Console application that uses that DLL (i.e. if in Visual Studio you now have a three-project solution: library with the bulk of the code, GUI with just the Win Forms code, and Console with just your console code.)

    And yet another belated answer. I couldn't get any output to the console created with AllocConsole as per earlier suggestions, so instead I'm starting with Console application. Then, if the console is not needed:

            [DllImport("kernel32.dll")]
            private static extern IntPtr GetConsoleWindow();
            [DllImport("user32.dll")]
            private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
            private const int SW_HIDE = 0;
            private const int SW_SHOW = 5;
            [DllImport("user32.dll", SetLastError = true)]
            static extern uint GetWindowThreadProcessId(IntPtr hWnd, out int lpdwProcessId);
            public static bool HideConsole()
                var hwnd = GetConsoleWindow();
                GetWindowThreadProcessId(hwnd, out var pid);
                if (pid != Process.GetCurrentProcess().Id) // It's not our console - don't mess with it.
                    return false;
                ShowWindow(hwnd, SW_HIDE);
                return true;
    

    In wind32, console-mode applications are a completely different beast from the usual message-queue-receiving applications. They are declared and compile differently. You might create an application which has both a console part and normal window and hide one or the other. But suspect you will find the whole thing a bit more work than you thought.

    Create a Windows Forms Application. Set project properties in application to type console application. The program will open a console window and show also the forms.

    Call Console.Writeline() from the forms or the Program.cs to send messages to the console window.

    You can comment in Program.cs

    // Application.EnableVisualStyles();
    // Application.SetCompatibleTextRenderingDefault(false);
    // Application.Run(new Form1());
    

    to avoid using Form1.

    Tested with C# and VS2019.

    Thanks for contributing an answer to Stack Overflow!

    • Please be sure to answer the question. Provide details and share your research!

    But avoid

    • Asking for help, clarification, or responding to other answers.
    • Making statements based on opinion; back them up with references or personal experience.

    To learn more, see our tips on writing great answers.