Skip to main content

使用控制台输出

默认生成的代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Test01
{
    internal static class Program
    {
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        /// 
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Test01());
        }
    }
}

修改后代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Runtime.InteropServices; // 添加

namespace Test01
{
    internal static class Program
    {
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        /// 
        [DllImport("kernel32.dll")] // 添加
        public static extern bool AllocConsole(); // 添加
        [DllImport("kernel32.dll")] // 添加
        static extern bool FreeConsole(); // 添加
        [STAThread]
        static void Main()
        {
            AllocConsole(); // 添加
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Test01());
            FreeConsole(); // 添加
        }
    }
}

注:在Visual Studio中运行时虽然有控制台窗口出现,但输出的内容还是在原来输出面板里,直接打开生成的exe文件的方式运行才会在控制台窗口里输出