在視窗程式中開啟控制檯
阿新 • • 發佈:2019-02-14
using System; using System.Runtime.InteropServices; using System.Windows.Forms; namespace WindowsFormsApp1 { public partial class Form1 : Form { // 啟動控制檯 [DllImport("kernel32.dll", CharSet = CharSet.Auto)] public static extern bool AllocConsole(); // 釋放控制檯 [DllImport("kernel32.dll", CharSet = CharSet.Auto)] public static extern bool FreeConsole(); public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { AllocConsole(); } private void Form1_FormClosing(object sender, FormClosingEventArgs e) { FreeConsole(); } private void button1_Click(object sender, EventArgs e) { //輸出時間和不同顏色 Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine(@"[{0}] {1}", DateTimeOffset.Now, "紅色文字"); Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine(@"[{0}] {1}", DateTimeOffset.Now, "Hello! world."); } } }