隐藏控制台窗口的方法

在我们做程序的过程中,往往都需要用到控制台的程序来做实验或者用作后台的一些小应用的时候我们通常能够用到控制台程序,而,很多时候我们不需要去展现他得窗口,如何去隐藏他得窗口呢?很简单……

首先先看一段简单的程序,这段程序就是我们用来去隐藏窗口的方法了!

View Code
#region 隐藏窗口
[DllImport("user32.dll", EntryPoint = "ShowWindow", SetLastError = true)]
private static extern bool ShowWindow(IntPtr hWnd, uint nCmdShow);
[DllImport("user32.dll", EntryPoint = "FindWindow", SetLastError = true)]
private static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

public static void WindowHide(string consoleTitle)
{
IntPtr a = FindWindow("ConsoleWindowClass", consoleTitle);
if (a != IntPtr.Zero)
ShowWindow(a, 0);//隐藏窗口
else
throw new Exception("can't hide console window");
}
#endregion

这段代码里面调用windows的api,很简单的就能够实现隐藏窗口的方法,至于更细致的东西,还是查一下google吧!

调用的方法:

View Code
 static void Main(string[] args)
{
try
{
Console.Title = "TestPmars"; //为控制台窗体指定一个标题,便于定位和区分
WindowHide("TestPmars");
}
catch
{
Console.WriteLine("出错了");
}
Thread.Sleep(-1);
}

很简单,Console.Title = "TestPmars",给控制台设定一个名字,之后将这个名字传给WindowHide就可以了!

其中我们用到的命名空间

using System.Runtime.InteropServices;

以上这些内容足以让我们实现隐藏窗口的目的了!

记在这里,分享给大家!

原文地址:https://www.cnblogs.com/pmars/p/2274737.html