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/

posted @ 2019-11-14 10:20  Net-Spider  阅读(2245)  评论(0编辑  收藏  举报