Winform中嵌入Console控制台

最近做了小软件,里面要用到实时显示日志;


本来呢,是自己做个累似的窗口,原理就是用定时读取文本文件,但是发现如果文本文件到了100K的时候,程序会显得很卡;


所以不得已还是得用Console控制台。


目前来说,网上有两种方法,一种是将项目的输出改成控制台方式;另一种就是调用win32 api来运行控制台...


本人更倾向于第二种方式;


但是在做的过程中碰到了一个问题,就是关闭控制台的话,整个程序就关闭掉了...这个问题我还无法解决。为了避免直接点击关闭按钮,在程序中把叉按钮灰掉了,这样就可以避免掉点击了~!


话不多说。贴源码


一个调用Win32 API的类

 

[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); //灰掉按钮

 

调用方法如下

 

AllocConsole(); IntPtr windowHandle = FindWindow(null, Process.GetCurrentProcess().MainModule.FileName); IntPtr closeMenu = GetSystemMenu(windowHandle, IntPtr.Zero); uint SC_CLOSE = 0xF060; RemoveMenu(closeMenu, SC_CLOSE, 0x0); for(int i=0;i<100;i++) { Console.WriteLine("i=:" + i); }

 

另外还可以调用 如下方法来改变标题的名称!

 

[DllImport("Kernel32.dll")] public static extern bool SetConsoleTitle(string strMessage);

你可能感兴趣的:(Winform中嵌入Console控制台)