简体   繁体   中英

How to write to a console window from a windows application?

Ever wondered how you could write out to a separate console window from your Windows application rather than writing to a log file? You might need to do that for a number of reasons – mostly related to debugging.

To do this programmatically, you can PInvoke the appropriate Win32 console functions (eg AllocConsole to create your own or AttachConsole to use another process's) from within your own code. This way you have the best control over what actually happens.

If you are OK with having a console window open alongside your other UI for the full lifetime of your process, you can simply change the project properties from within Visual Studio and choose "Console Application", simple as that:

VS 项目设置

Here's how you do it: Predefined APIs are available in kernel32.dll that will allow you to write to a console. The following shows a sample usage of the feature.

private void button1_Click(object sender, EventArgs e) 
{
     new Thread(new ThreadStart(delegate()
     {
        AllocConsole();
        for (uint i = 0; i < 1000000; ++i)
        {
            Console.WriteLine("Hello " + i);
        }

        FreeConsole();
    })).Start();
}

You'll need to import the AllocConsole and FreeConsole API from kernel32.dll.

[DllImport("kernel32.dll")]
public static extern bool AllocConsole();

[DllImport("kernel32.dll")]
public static extern bool FreeConsole();

And you can always make it Conditional if you want to use it only while debugging.

private void button1_Click(object sender, EventArgs e)
{
    new Thread(new ThreadStart(delegate()
    {
        AllocateConsole();
        for (uint i = 0; i < 1000000; ++i)
        {
            Console.WriteLine("Hello " + i);
        }

        DeallocateConsole();
    })).Start();
}


[Conditional("DEBUG")]
private void AllocateConsole()
{
    AllocConsole();
}

[Conditional("DEBUG")]
private void DeallocateConsole()
{
    FreeConsole();
}

If you have console application then do

System.Console.WriteLine("What ever you want");

If you have form application, you need to create console first:

http://www.csharp411.com/console-output-from-winforms-application/

You can console output from a Windows Forms application using kernel32.dll. For complete detail check this article .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM