Using Console.WriteLine() in Winform with .NET and .NET Core.
By using the Console.WriteLine() method in WinForm, you can output information in the console window. First, you need to import the console window into WinForm. This can be achieved by adding a reference to a console application in the project.
First, right-click on the project, choose “Add”-> “References”-> “Project”, then select “System”-> “Console”.
Next, use the following code in the WinForm’s code:
using System;
using System.Runtime.InteropServices;
public class MyConsole
{
[DllImport("kernel32.dll",
EntryPoint = "AllocConsole",
SetLastError = true,
CharSet = CharSet.Auto,
CallingConvention = CallingConvention.StdCall)]
private static extern int AllocConsole();
[DllImport("kernel32.dll",
EntryPoint = "FreeConsole",
SetLastError = true,
CharSet = CharSet.Auto,
CallingConvention = CallingConvention.StdCall)]
private static extern int FreeConsole();
}
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
MyConsole.AllocConsole();
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
MyConsole.FreeConsole();
}
private void button1_Click(object sender, EventArgs e)
{
Console.WriteLine("Hello, World!");
}
}
In this example, we allocate a console window by calling the MyConsole.AllocConsole() method in the Form1_Load event handler, and release the console window by calling the MyConsole.FreeConsole() method in the Form1_FormClosing event handler. When the button is clicked, “Hello, World!” will be output in the console window.