显示/隐藏 C# 控制台应用程序的控制台窗口

发布于 2024-09-16 08:35:55 字数 233 浏览 2 评论 0原文

我用谷歌搜索有关如何隐藏自己的控制台窗口的信息。令人惊讶的是,我能找到的唯一解决方案是涉及 FindWindow() 的 hacky 解决方案,通过其标题查找控制台窗口。我对 Windows API 进行了更深入的研究,发现有一种更好、更简单的方法,所以我想将其发布在这里供其他人查找。

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

I googled around for information on how to hide one’s own console window. Amazingly, the only solutions I could find were hacky solutions that involved FindWindow() to find the console window by its title. I dug a bit deeper into the Windows API and found that there is a much better and easier way, so I wanted to post it here for others to find.

How do you hide (and show) the console window associated with my own C# console application?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(10

孤凫 2024-09-23 08:35:55

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

Just go to the application's Properties and change the Output type from Console Application to Windows Application.

樱娆 2024-09-23 08:35:55

方法如下:

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

Here’s how:

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);
焚却相思 2024-09-23 08:35:55

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

如果 showConsoletrue,此代码将显示控制台

You could do the reversed and set the Application output type to: Windows Application. Then add this code to the beginning of the 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
}

This code will show the Console if showConsole is true

柠檬 2024-09-23 08:35:55

如果您想隐藏控制台本身,为什么需要控制台应用程序? =)

我建议将项目输出类型设置为Windows 应用程序,而不是控制台应用程序。它不会显示控制台窗口,但会执行所有操作,就像控制台应用程序一样。

Why do you need a console application if you want to hide console itself? =)

I recommend setting Project Output type to Windows Application instead of Console application. It will not show you console window, but execute all actions, like Console application do.

離人涙 2024-09-23 08:35:55

请参阅我的帖子:

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

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

See my post here:

Show Console in Windows Application

You can make a Windows application (with or without the window) and show the console as desired. Using this method the console window never appears unless you explicitly show it. I use it for dual-mode applications that I want to run in either console or gui mode depending on how they are opened.

堇年纸鸢 2024-09-23 08:35:55

“只是为了隐藏”,您可以:

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

而不是Console.Readline/key 您可以在最后使用 new ManualResetEvent(false).WaitOne() 来保持应用程序运行。

"Just to hide" you can:

Change the output type from Console Application to Windows Application,

And Instead of Console.Readline/key you can use new ManualResetEvent(false).WaitOne() at the end to keep the app running.

愁以何悠 2024-09-23 08:35:55

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

Following from Timwi's answer, I've created a helper class to wrap the needed code:

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
    }
}
荒路情人 2024-09-23 08:35:55

如果您不想依赖于窗口标题,请使用以下命令:

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

If you don't want to depends on window title use this :

    [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());
泡沫很甜 2024-09-23 08:35:55

如果您在集成小批量应用程序时没有问题,可以使用这个名为 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 添加到解决方案中,将构建操作设置为“内容”,将“复制到输出目录”设置为适合您的内容,cmdow 将在运行时隐藏控制台窗口。

要使控制台再次可见,您只需更改参数

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

If you don't have a problem integrating a small batch application, there is this program called Cmdow.exe that will allow you to hide console windows based on console title.

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

Add the exe to the solution, set the build action to "Content", set Copy to Output Directory to what suits you, and cmdow will hide the console window when it is ran.

To make the console visible again, you just change the Arguments

HideConsole.StartInfo.Arguments = "MyConsole /Vis";
弱骨蛰伏 2024-09-23 08:35:55

要在使用 csc 编译器时将输出类型从控制台应用程序更改为 Windows 应用程序,请将 -target:winexe 添加到 csc.exe 命令中,如下所示:
C:\Windows\Microsoft.NET\Framework\v4.0.30319\csc.exe -out:example.exe -target:winexe example.cs

To change the Output type from Console Application to Windows Application when using csc compiler add -target:winexe to the csc.exe command like that:
C:\Windows\Microsoft.NET\Framework\v4.0.30319\csc.exe -out:example.exe -target:winexe example.cs

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文