控制台作为信息显示窗口对于调试程序查找程序BUG有诸多好处,所以给GUI程序绑定一个控制台窗口用于显示程序运行时的状态是非常有必要的,否则就需要用WinForm的控件自己去实现了。首先想让WinForm程序绑定控制台窗口需要调用Windows API,需要先导入命名空间:
using System.Runtime.InteropServices;
然后导入dll:
[DllImport("kernel32.dll")]
public static extern bool AllocConsole();
[DllImport("kernel32.dll")]
public static extern bool FreeConsole();
然后在构造函数中关联一个控制台:
AllocConsole(); //关联一个控制台窗口用于显示信息
释放关联的控制台:
FreeConsole();//释放关联的控制台,不然会报错
在设计窗口上点击窗口,不要点击窗口上的控件,设置窗口关闭前的回调函数:
再弄一个按钮控件用于测试向控制台输出字符串:
System.Console.WriteLine("春哥纯爷们!");
下面是完整的示例:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Runtime.InteropServices;
//此文件存放的是窗口控件的回调函数
namespace Untrie
{
public partial class Form1 : Form
{
[DllImport("kernel32.dll")]
public static extern bool AllocConsole();//关联一个控制台窗口
[DllImport("kernel32.dll")]
public static extern bool FreeConsole();//释放关联的控制台窗口
public Form1()
{
InitializeComponent();
AllocConsole(); //关联一个控制台窗口用于显示信息
}
private void button1_Click(object sender, EventArgs e)
{
System.Console.WriteLine("春哥纯爷们!");
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
//窗口关闭前 回调函数
FreeConsole();//释放关联的控制台,不然会报错
}
}
}
清除控制台窗口中的内容:
System.Console.Clear();