需求描述:在做硬體調試的時候,經常會需要用程式調試具體問題處在哪裡,但是不斷重新開機程式看日志顯得繁瑣,想将日志及調試結果實時輸出。
解決方案:使用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到的部分代碼有引用,但已找不到來源,如有侵權,請聯系删除。