Tim*_*mwi 177 c# console console-application
我搜索了有关如何隐藏自己的控制台窗口的信息.令人惊讶的是,我能找到的唯一解决方案是通过其标题FindWindow()找到控制台窗口的 hacky解决方案.我深入挖掘了Windows API,发现有更好更简单的方法,所以我想在这里发布,供其他人查找.
如何隐藏(和显示)与我自己的C#控制台应用程序关联的控制台窗口?
Tim*_*mwi 244
这是如何做:
using System.Runtime.InteropServices;
Run Code Online (Sandbox Code Playgroud)
[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;
Run Code Online (Sandbox Code Playgroud)
var handle = GetConsoleWindow();
// Hide
ShowWindow(handle, SW_HIDE);
// Show
ShowWindow(handle, SW_SHOW);
Run Code Online (Sandbox Code Playgroud)
小智 243
只需转到应用程序的属性,然后将输出类型从控制台应用程序更改为Windows应用程序.
Sas*_*sha 24
如果要隐藏控制台本身,为什么还需要控制台应用程序?=)
我建议将Project Output类型设置为Windows Application而不是Console应用程序.它不会向您显示控制台窗口,但会执行所有操作,例如控制台应用程序.
Mai*_*gma 17
您可以执行相反的操作并将Application输出类型设置为:Windows Application.然后将此代码添加到应用程序的开头.
[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
}
Run Code Online (Sandbox Code Playgroud)
如果showConsole是,此代码将显示控制台true
小智 9
在这里看我的帖子:
您可以创建Windows应用程序(带或不带窗口)并根据需要显示控制台.使用此方法,除非您明确显示,否则控制台窗口永远不会出现.我将它用于双模式应用程序,我想在控制台或gui模式下运行,具体取决于它们的打开方式.
“只是为了隐藏”你可以:
将输出类型从Console Application更改为Windows Application,
而不是Console.Readline/key你可以new ManualResetEvent(false).WaitOne()在最后使用来保持应用程序运行。
小智 7
根据Timwi的回答,我创建了一个辅助类来包装所需的代码:
using System;
using System.Runtime.InteropServices;
static class ConsoleExtension {
const int SW_HIDE = 0;
const int SW_SHOW = 5;
readonly static IntPtr handle = GetConsoleWindow();
[DllImport("kernel32.dll")] static extern IntPtr GetConsoleWindow();
[DllImport("user32.dll")] static extern bool ShowWindow(IntPtr hWnd,int nCmdShow);
public static void Hide() {
ShowWindow(handle,SW_HIDE); //hide the console
}
public static void Show() {
ShowWindow(handle,SW_SHOW); //show the console
}
}
Run Code Online (Sandbox Code Playgroud)