windows form .. console.writeline() where is console?

后端 未结 4 1956
情深已故
情深已故 2020-12-08 09:13

I created a windows form solution and in the constructor of a class I called

Console.WriteLine(\"constructer called\")

But I only got the form

4条回答
  •  失恋的感觉
    2020-12-08 09:41

    As other answers have stated System.Diagnostics.Debug.WriteLine is the right call for debugging messages. But to answer your question:

    From a Winforms application you can invoke a console window for interaction like this:

    using System.Runtime.InteropServices;
    
    ...
    
    void MyConsoleHandler()
    {
        if (AllocConsole())
        {
            Console.Out.WriteLine("Input some text here: ");
            string UserInput = Console.In.ReadLine();
    
            FreeConsole();
        }
    }
    
    
    [DllImport("kernel32.dll", SetLastError = true)]
    [return: MarshalAs(UnmanagedType.Bool)]
    static extern bool AllocConsole();
    
    [DllImport("kernel32.dll", SetLastError = true)]
    [return: MarshalAs(UnmanagedType.Bool)]
    static extern bool FreeConsole();
    

    I sometimes use this to raise a command prompt instead of application windows when given certain switches on opening.

    There's some more ideas in this similar question if anyone needs it:
    What is the Purpose of Console.WriteLine() in Winforms

提交回复
热议问题