我在谷歌上到处寻找如何隐藏自己的控制台窗口的信息。令人惊讶的是,我能找到的唯一解决方案就是那些让FindWindow()
根据标题找到控制台窗口的老套解决方案。我更深入地研究了Windows API,发现有一种更好、更简单的方法,所以我想在这里发布它,供其他人查找。
如何隐藏(和显示)与我自己的C#控制台应用程序关联的控制台窗口?
发布于 2010-08-26 10:19:49
下面是操作步骤:
using System.Runtime.InteropServices;
[DllImport("kernel32.dll")]
static extern IntPtr GetConsoleWindow();
[DllImport("user32.dll")]
static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
const int SW_HIDE = 0;
const int SW_SHOW = 5;
var handle = GetConsoleWindow();
// Hide
ShowWindow(handle, SW_HIDE);
// Show
ShowWindow(handle, SW_SHOW);
发布于 2011-05-01 21:09:05
只需转到应用程序的属性,并将输出类型从控制台应用程序更改为Windows应用程序。
发布于 2015-11-04 16:00:29
您可以执行相反的操作,并将应用程序输出类型设置为: Windows应用程序。然后将此代码添加到应用程序的开头。
[DllImport("kernel32.dll", EntryPoint = "GetStdHandle", SetLastError = true, CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
public static extern IntPtr GetStdHandle(int nStdHandle);
[DllImport("kernel32.dll", EntryPoint = "AllocConsole", SetLastError = true, CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
public static extern int AllocConsole();
private const int STD_OUTPUT_HANDLE = -11;
private const int MY_CODE_PAGE = 437;
private static bool showConsole = true; //Or false if you don't want to see the console
static void Main(string[] args)
{
if (showConsole)
{
AllocConsole();
IntPtr stdHandle = GetStdHandle(STD_OUTPUT_HANDLE);
Microsoft.Win32.SafeHandles.SafeFileHandle safeFileHandle = new Microsoft.Win32.SafeHandles.SafeFileHandle(stdHandle, true);
FileStream fileStream = new FileStream(safeFileHandle, FileAccess.Write);
System.Text.Encoding encoding = System.Text.Encoding.GetEncoding(MY_CODE_PAGE);
StreamWriter standardOutput = new StreamWriter(fileStream, encoding);
standardOutput.AutoFlush = true;
Console.SetOut(standardOutput);
}
//Your application code
}
如果showConsole
为true
,则此代码将显示控制台
https://stackoverflow.com/questions/3571627
复制相似问题