Display the console output in the Windows window application
When developing the Windows window application, you may encounter situations that need to display the console output. By default, the Windows window application has no visible console window.
Consider the following code fragment:
using System.Windows.Forms;
class test
{
static void Main()
{
Console.WriteLine("test");
MessageBox.Show("test");
}
}
Copy after login
If you compile it as a console application, you will see the output and message box of the console. However, if you compile it to the Windows Window Application (/Target: Winexe), there will only be a message box.
To display the console in the Windows window application, you can use the following code:
using System.Runtime.InteropServices;
private void Form1_Load(object sender, EventArgs e)
{
AllocConsole();
}
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool AllocConsole();
Copy after login
This code calls the AloCConsole function in the kernel32.dll library, which will create a new console window in your application. Once this function is called, any subsequent console output call will be displayed in the newly created window.
The above is the detailed content of How to Show Console Output in a Windows Forms Application?. For more information, please follow other related articles on the PHP Chinese website!