WinForm程序调用并Host控制台的方法
做一个小工具,想把一些输出信息使用控制台来显示。一种方式,采用Log4Net;第二种方式,自己编码。
网上查了一些资料,需要用WIN32API来实现。实现代码如下:
1、Import API

[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);
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);
2、Winfom代码

AllocConsole();
IntPtr windowHandle = FindWindow(null, Process.GetCurrentProcess().MainWindowTitle /*Process.GetCurrentProcess().MainModule.*/);
IntPtr closeMenu = GetSystemMenu(windowHandle, IntPtr.Zero);
ShowWindow(windowHandle, 1);//显示
uint SC_CLOSE = 0xF060;//移除关闭按钮
UserAPIHelper.RemoveMenu(closeMenu, SC_CLOSE, 0x0);
consoleTitle = this.Text + "-输出控制台";
Console.Title = consoleTitle;
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("欢迎!!!");
IntPtr windowHandle = FindWindow(null, Process.GetCurrentProcess().MainWindowTitle /*Process.GetCurrentProcess().MainModule.*/);
IntPtr closeMenu = GetSystemMenu(windowHandle, IntPtr.Zero);
ShowWindow(windowHandle, 1);//显示
uint SC_CLOSE = 0xF060;//移除关闭按钮
UserAPIHelper.RemoveMenu(closeMenu, SC_CLOSE, 0x0);
consoleTitle = this.Text + "-输出控制台";
Console.Title = consoleTitle;
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("欢迎!!!");
注意的一点是使用Process.GetCurrentProcess().MainWindowTitle 来获取窗口句柄,如果使用FileName,当你通过桌面快捷方式启动程序时,无法获取到窗口句柄,从而无法移除关闭按钮。
原因:在快捷方式启动程序时,窗口的FileName不包含Exe所在路径,而直接运行Exe文件FileName显示的是exe的全路径。
效果图:
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具