1. 程式人生 > >程式執行時,建立一個額外的輸出臺,輸出程式內的Log以及除錯結果

程式執行時,建立一個額外的輸出臺,輸出程式內的Log以及除錯結果

需求描述:在做硬體除錯的時候,經常會需要用程式除錯具體問題處在哪裡,但是不斷重啟程式看日誌顯得繁瑣,想將日誌及除錯結果實時輸出。 解決方案:使用Kernel32.dll和user32.dll建立Console,使用控制檯實時輸出。在Main函式中新增實現程式碼

程式碼如下:

using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace Form_E
{
    static class Program
    {
        [DllImport("Kernel32.dll")]
        private static extern bool AllocConsole();
        [DllImport("kernel32.dll", EntryPoint = "FreeConsole")]
        private static extern bool FreeConsole();
        [DllImport("user32.dll", EntryPoint = "FindWindow")]
        extern static IntPtr FindWindow(string lpClassName, string lpWindowName);
        [DllImport("user32.dll", EntryPoint = "GetSystemMenu")]
        extern static IntPtr GetSystemMenu(IntPtr hWnd, IntPtr bRevert);
        [DllImport("user32.dll", EntryPoint = "RemoveMenu")]
        extern static IntPtr RemoveMenu(IntPtr hMenu, uint uPosition, uint uFlags);
        [DllImport("Kernel32.dll")]
        public static extern bool SetConsoleTitle(string strMessage);

        /// <summary>
        /// 應用程式的主入口點。
        /// </summary>
        [STAThread]
        static void Main()
        {
            AllocConsole();
            IntPtr windowHandle = FindWindow(null, Process.GetCurrentProcess().MainModule.FileName);
            IntPtr closeMenu = GetSystemMenu(windowHandle, IntPtr.Zero);
            uint SC_CLOSE = 0xF060;
            RemoveMenu(closeMenu, SC_CLOSE, 0x0);
            SetConsoleTitle("除錯資訊");

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

            FreeConsole();
        }
    }
}

其他:Google到的部分程式碼有引用,但已找不到來源,如有侵權,請聯絡刪除。