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);   
复制代码

 

 

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(
"欢迎!!!");
复制代码

 

注意的一点是使用Process.GetCurrentProcess().MainWindowTitle 来获取窗口句柄,如果使用FileName,当你通过桌面快捷方式启动程序时,无法获取到窗口句柄,从而无法移除关闭按钮。

原因:在快捷方式启动程序时,窗口的FileName不包含Exe所在路径,而直接运行Exe文件FileName显示的是exe的全路径。

 

效果图:

posted @   伸手不见五趾  阅读(698)  评论(0编辑  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· 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工具
点击右上角即可分享
微信分享提示