我在谷歌上搜索如何隐藏自己的控制台窗口的信息。令人惊讶的是,我能找到的唯一解决方案是使用FindWindow()根据标题查找控制台窗口的俗气解决方案。我深入研究了一下Windows API,发现有一种更好更简单的方法,所以我想把它贴在这里,让其他人找到。

如何隐藏(并显示)与我自己的c#控制台应用程序相关联的控制台窗口?


当前回答

“只是为了隐藏”你可以:

将输出类型从控制台应用程序更改为Windows应用程序,

而不是主机。你可以在最后使用new ManualResetEvent(false). waitone()来保持应用程序运行。

其他回答

请看我的帖子:

在Windows应用程序中显示控制台

您可以创建一个Windows应用程序(带或不带窗口)并根据需要显示控制台。使用此方法,控制台窗口永远不会出现,除非显式地显示它。我将它用于双模式应用程序,我想在控制台或gui模式下运行,这取决于它们是如何打开的。

方法如下:

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);

“只是为了隐藏”你可以:

将输出类型从控制台应用程序更改为Windows应用程序,

而不是主机。你可以在最后使用new ManualResetEvent(false). waitone()来保持应用程序运行。

如果你不想依赖于窗口标题,请使用以下方法:

    [DllImport("user32.dll")]
    static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

...

    IntPtr h = Process.GetCurrentProcess().MainWindowHandle;
    ShowWindow(h, 0);
    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);
    Application.Run(new FormPrincipale());

你可以做相反的操作,将应用程序输出类型设置为: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
}

如果showConsole为真,这段代码将显示控制台