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

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


当前回答

如果你对集成一个小批量应用程序没有问题,有一个叫做Cmdow.exe的程序,它可以让你根据控制台标题隐藏控制台窗口。

Console.Title = "MyConsole";
System.Diagnostics.Process HideConsole = new System.Diagnostics.Process();
HideConsole.StartInfo.UseShellExecute = false;
HideConsole.StartInfo.Arguments = "MyConsole /hid";
HideConsole.StartInfo.FileName = "cmdow.exe";
HideConsole.Start();

将exe添加到解决方案中,将构建操作设置为“Content”,将Copy设置为适合您的输出目录,并且cmdow在运行时将隐藏控制台窗口。

要使控制台再次可见,只需更改Arguments

HideConsole.StartInfo.Arguments = "MyConsole /Vis";

其他回答

根据Timwi的回答,我已经创建了一个helper类来包装所需的代码:

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
    }
}

只需转到应用程序的属性,并将输出类型从控制台应用程序更改为Windows应用程序。

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

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

方法如下:

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应用程序中显示控制台

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