需求描述:在做硬件调试的时候,经常会需要用程序调试具体问题处在哪里,但是不断重启程序看日志显得繁琐,想将日志及调试结果实时输出。
解决方案:使用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到的部分代码有引用,但已找不到来源,如有侵权,请联系删除。