原文鏈接:C#之winform控制台打印輸出、打印調試——CSDN
在Qt中,經常使用qDebug()<<"Hello World";的方式往控制台打印一些輸出,以便觀察程序的運行情況。
在Java中(eclipse、myeclipse中),經常使用的是System.out.println("Hello World");的方式。
在Android中,經常使用的是Log.d("Hello World");
. . .
在C#的時候,使用的是Console.WriteLine("Hello World");
開發winform的時候,需要先往主函數所在的源文件中加入以下內容。
引入庫:
using System.Runtime.InteropServices;
在Main()前,添加:
[DllImport("kernel32.dll")]
public static extern bool AllocConsole();
[DllImport("kernel32.dll")]
static extern bool FreeConsole();
在Main()中,第一行添加:
AllocConsole();
在Main()中,最后一行添加:
FreeConsole();
示例:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
// 控制台輸出,需加入此庫
using System.Runtime.InteropServices;
namespace HelloWorld_WindowsForm
{
static class Program
{
[DllImport("kernel32.dll")]
public static extern bool AllocConsole();
[DllImport("kernel32.dll")]
static extern bool FreeConsole();
/// <summary>
/// 應用程序的主入口點。
/// </summary>
[STAThread]
static void Main()
{
// 允許調用控制台輸出
AllocConsole();
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new LoginPage());
// 釋放
FreeConsole();
}
}
}
