C#WinForm程序顯示控制台窗口Console


啟動一個WINFORM項目,使用一些API函數將控制台顯示出來: AllocConsole 和 FreeConsole。

本程序只在DEBUG模式下顯示控制台

 

 




老規矩,廢話不多說,貼代碼


using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Threading;

namespace WindowsFormsStartConsole
{
    static class Program
    {
        [DllImport("kernel32.dll")]
        public static extern Boolean AllocConsole();
        [DllImport("kernel32.dll")]
        public static extern Boolean FreeConsole();

        /// <summary>
        /// 應用程序的主入口點。
        /// </summary>
        [STAThread]
        static void Main()
        {

#if DEBUG
            AllocConsole();
            Shell.WriteLine("注意:啟動程序...");
            Shell.WriteLine("\tWritten by wuming");
            Shell.WriteLine("{0}:{1}", "警告", "這是一條警告信息。");
            Shell.WriteLine("{0}:{1}", "錯誤", "這是一條錯誤信息!");
            Shell.WriteLine("{0}:{1}", "注意", "這是一條需要的注意信息。");
            Shell.WriteLine("");
#endif  

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());

#if DEBUG
            Shell.WriteLine("注意:2秒后關閉...");
            Thread.Sleep(1000);
            Shell.WriteLine("注意:1秒后關閉...");
            Thread.Sleep(1000);
            Shell.WriteLine("注意:正在關閉...");
            Thread.Sleep(100);
            FreeConsole();
#endif
        }
    }


    static class Shell
    {
        /// <summary>  
        /// 輸出信息  
        /// </summary>  
        /// <param name="format"></param>  
        /// <param name="args"></param>  
        public static void WriteLine(string format, params object[] args)
        {
            WriteLine(string.Format(format, args));
        }

        /// <summary>  
        /// 輸出信息  
        /// </summary>  
        /// <param name="output"></param>  
        public static void WriteLine(string output)
        {
            Console.ForegroundColor = GetConsoleColor(output);
            Console.WriteLine(@"[{0}]{1}", DateTimeOffset.Now, output);
        }

        /// <summary>  
        /// 根據輸出文本選擇控制台文字顏色  
        /// </summary>  
        /// <param name="output"></param>  
        /// <returns></returns>  
        private static ConsoleColor GetConsoleColor(string output)
        {
            if (output.StartsWith("警告")) return ConsoleColor.Yellow;
            if (output.StartsWith("錯誤")) return ConsoleColor.Red;
            if (output.StartsWith("注意")) return ConsoleColor.Green;
            return ConsoleColor.Gray;
        }
    }  
}

————————————————
版權聲明:本文為CSDN博主「無0_0名」的原創文章,遵循 CC 4.0 BY-SA 版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/b510030/article/details/52621312/


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM