WinForm程序调用并Host控制台的方法
做一个小工具,想把一些输出信息使用控制台来显示。一种方式,采用Log4Net;第二种方式,自己编码。
网上查了一些资料,需要用WIN32API来实现。实现代码如下:
1、Import API
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
[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代码
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
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的全路径。
效果图: