如何在隐藏控制台的情况下运行 C# 控制台应用程序

发布于 2024-07-18 19:32:16 字数 92 浏览 7 评论 0原文

有没有办法在执行控制台应用程序时隐藏控制台窗口?

我当前正在使用 Windows 窗体应用程序来启动控制台进程,但我不希望在任务运行时显示控制台窗口。

Is there a way to hide the console window when executing a console application?

I am currently using a Windows Forms application to start a console process, but I don't want the console window to be displayed while the task is running.

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

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

发布评论

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

评论(13

╰沐子 2024-07-25 19:32:16

如果您编写了控制台应用程序,则可以将其默认隐藏。

创建一个新的控制台应用程序,然后将“输出类型”类型更改为“Windows 应用程序”(在项目属性中完成)

If you wrote the console application you can make it hidden by default.

Create a new console app then then change the "Output Type" type to "Windows Application" (done in the project properties)

牵强ㄟ 2024-07-25 19:32:16

如果您使用的是 ProcessStartInfo 类,您可以将窗口样式设置为隐藏 - 对于控制台(非 GUI)应用程序,您必须将 CreateNoWindow 设置为 true:

System.Diagnostics.ProcessStartInfo start =
      new System.Diagnostics.ProcessStartInfo();
start.FileName = dir + @"\Myprocesstostart.exe";
start.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; //Hides GUI
start.CreateNoWindow = true; //Hides console

If you are using the ProcessStartInfo class you can set the window style to hidden - in the case of console (not GUI) applications, you have to set CreateNoWindow to true:

System.Diagnostics.ProcessStartInfo start =
      new System.Diagnostics.ProcessStartInfo();
start.FileName = dir + @"\Myprocesstostart.exe";
start.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; //Hides GUI
start.CreateNoWindow = true; //Hides console
昔日梦未散 2024-07-25 19:32:16

如果您使用的是 Process 类,那么您可以

yourprocess.StartInfo.UseShellExecute = false;
yourprocess.StartInfo.CreateNoWindow = true;

yourprocess.start(); 之前编写,并且进程将被隐藏

If you are using Process Class then you can write

yourprocess.StartInfo.UseShellExecute = false;
yourprocess.StartInfo.CreateNoWindow = true;

before yourprocess.start(); and process will be hidden

嘴硬脾气大 2024-07-25 19:32:16

简单的答案是:转到控制台应用程序的属性(项目的属性)。在“应用程序”选项卡中,只需将“输出类型”更改为“Windows 应用程序”。 就这样。

Simple answer is that: Go to your console app's properties(project's properties).In the "Application" tab, just change the "Output type" to "Windows Application". That's all.

今天小雨转甜 2024-07-25 19:32:16

您可以使用FreeConsole 将控制台与进程分离的 API :(

[DllImport("kernel32.dll")]
static extern bool FreeConsole();

当然,这仅适用于您有权访问控制台应用程序的源代码的情况)

You can use the FreeConsole API to detach the console from the process :

[DllImport("kernel32.dll")]
static extern bool FreeConsole();

(of course this is applicable only if you have access to the console application's source code)

眼眸里的那抹悲凉 2024-07-25 19:32:16

如果您对输出感兴趣,可以使用此函数:

private static string ExecCommand(string filename, string arguments)
{
    Process process = new Process();
    ProcessStartInfo psi = new ProcessStartInfo(filename);
    psi.Arguments = arguments;
    psi.CreateNoWindow = true;
    psi.RedirectStandardOutput = true;
    psi.RedirectStandardError = true;
    psi.UseShellExecute = false;
    process.StartInfo = psi;

    StringBuilder output = new StringBuilder();
    process.OutputDataReceived += (sender, e) => { output.AppendLine(e.Data); };
    process.ErrorDataReceived += (sender, e) => { output.AppendLine(e.Data); };

    // run the process
    process.Start();

    // start reading output to events
    process.BeginOutputReadLine();
    process.BeginErrorReadLine();

    // wait for process to exit
    process.WaitForExit();

    if (process.ExitCode != 0)
        throw new Exception("Command " + psi.FileName + " returned exit code " + process.ExitCode);

    return output.ToString();
}

它运行给定的命令行程序,等待其完成并将输出作为字符串返回。

If you're interested in the output, you can use this function:

private static string ExecCommand(string filename, string arguments)
{
    Process process = new Process();
    ProcessStartInfo psi = new ProcessStartInfo(filename);
    psi.Arguments = arguments;
    psi.CreateNoWindow = true;
    psi.RedirectStandardOutput = true;
    psi.RedirectStandardError = true;
    psi.UseShellExecute = false;
    process.StartInfo = psi;

    StringBuilder output = new StringBuilder();
    process.OutputDataReceived += (sender, e) => { output.AppendLine(e.Data); };
    process.ErrorDataReceived += (sender, e) => { output.AppendLine(e.Data); };

    // run the process
    process.Start();

    // start reading output to events
    process.BeginOutputReadLine();
    process.BeginErrorReadLine();

    // wait for process to exit
    process.WaitForExit();

    if (process.ExitCode != 0)
        throw new Exception("Command " + psi.FileName + " returned exit code " + process.ExitCode);

    return output.ToString();
}

It runs the given command line program, waits for it to finish and returns the output as string.

屋檐 2024-07-25 19:32:16

如果您正在创建一个不需要用户输入的程序,您始终可以将其创建为服务。 服务不会显示任何类型的 UI。

If you're creating a program that doesn't require user input you could always just create it as a service. A service won't show any kind of UI.

ヅ她的身影、若隐若现 2024-07-25 19:32:16

将其添加到您的类中以导入 DLL 文件:

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

[DllImport("kernel32.dll")] 
static extern IntPtr GetConsoleWindow();

const int SW_HIDE = 0;
const int SW_SHOW = 5;

然后,如果您想隐藏它,请使用此命令:

 var handle = GetConsoleWindow();
 ShowWindow(handle, SW_HIDE);

如果您想显示控制台:

var handle = GetConsoleWindow();
ShowWindow(handle, SW_SHOW);

Add this to your class to import the DLL file:

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

[DllImport("kernel32.dll")] 
static extern IntPtr GetConsoleWindow();

const int SW_HIDE = 0;
const int SW_SHOW = 5;

And then if you want to hide it use this command:

 var handle = GetConsoleWindow();
 ShowWindow(handle, SW_HIDE);

And if you want to show the console:

var handle = GetConsoleWindow();
ShowWindow(handle, SW_SHOW);
兰花执着 2024-07-25 19:32:16

我有一个通用的解决方案可以分享:

using System;
using System.Runtime.InteropServices;

namespace WhateverNamepaceYouAreUsing
{
    class Magician
    {
        [DllImport("kernel32.dll")]
        static extern IntPtr GetConsoleWindow();

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

        const int HIDE = 0;
        const int SHOW = 5;

        public static void DisappearConsole()
        {
            ShowWindow(GetConsoleWindow(), HIDE);
        }
    }
}

只需将此类包含在您的项目中,然后调用 Magician.DisappearConsole(); 即可。

当您通过单击启动程序时,控制台会闪烁。 从命令提示符执行时,命令提示符在执行后很快就会消失。

我为一个 Discord Bot 执行此操作,它作为一个不可见的进程永远在我的计算机后台运行。 这比让 TopShelf 为我工作更容易。 在我在其他地方找到的代码的帮助下写这篇文章之前,一些 TopShelf 教程让我失败了。 ;P

我也尝试简单地更改 Visual Studio 中的设置 > 项目>> 属性> 应用程序作为 Windows 应用程序而不是控制台应用程序启动,而我的项目的某些内容阻止了它隐藏我的控制台 - 也许是因为 DSharpPlus 要求在启动时启动控制台。 我不知道。 不管出于什么原因,这个类允许我在控制台弹出后轻松地杀死它。

希望这位魔术师能帮助别人。 ;)

I've got a general solution to share:

using System;
using System.Runtime.InteropServices;

namespace WhateverNamepaceYouAreUsing
{
    class Magician
    {
        [DllImport("kernel32.dll")]
        static extern IntPtr GetConsoleWindow();

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

        const int HIDE = 0;
        const int SHOW = 5;

        public static void DisappearConsole()
        {
            ShowWindow(GetConsoleWindow(), HIDE);
        }
    }
}

Just include this class in your project, and call Magician.DisappearConsole();.

A console will flash when you start the program by clicking on it. When executing from the command prompt, the command prompt disappears very shortly after execution.

I do this for a Discord Bot that runs forever in the background of my computer as an invisible process. It was easier than getting TopShelf to work for me. A couple TopShelf tutorials failed me before I wrote this with some help from code I found elsewhere. ;P

I also tried simply changing the settings in Visual Studio > Project > Properties > Application to launch as a Windows Application instead of a Console Application, and something about my project prevented this from hiding my console - perhaps because DSharpPlus demands to launch a console on startup. I don't know. Whatever the reason, this class allows me to easily kill the console after it pops up.

Hope this Magician helps somebody. ;)

暗地喜欢 2024-07-25 19:32:16

我知道我没有完全回答你想要的问题,但我想知道你是否问了正确的问题。

为什么不使用以下任一方法:

  1. Windows 服务
  2. 创建一个新线程并在该线程上运行您的进程

如果您想要的只是运行一个进程,那么这些听起来像是更好的选择。

I know I'm not answering exactly what you want, but I am wondering if you're asking the right question.

Why don't you use either:

  1. windows service
  2. create a new thread and run your process on that

Those sound like better options if all you want is to run a process.

ぽ尐不点ル 2024-07-25 19:32:16

尽管正如此处的其他答案所说,您可以将“输出类型”更改为“Windows 应用程序”,但请注意,这意味着您无法使用 Console.In 因为它将成为 NullStreamReader。

Console.OutConsole.Error 似乎仍然可以正常工作。

Although as other answers here have said you can change the "Output type" to "Windows Application", please be aware that this will mean that you cannot use Console.In as it will become a NullStreamReader.

Console.Out and Console.Error seem to still work fine however.

揪着可爱 2024-07-25 19:32:16

根据上面 Adam Markowitz 的回答,以下内容对我有用:

process = new Process();
process.StartInfo = new ProcessStartInfo("cmd.exe", "/k \"" + CmdFilePath + "\"");
process.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
//process.StartInfo.UseShellExecute = false;
//process.StartInfo.CreateNoWindow = true;
process.Start();

Based on Adam Markowitz's answer above, following worked for me:

process = new Process();
process.StartInfo = new ProcessStartInfo("cmd.exe", "/k \"" + CmdFilePath + "\"");
process.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
//process.StartInfo.UseShellExecute = false;
//process.StartInfo.CreateNoWindow = true;
process.Start();
墨离汐 2024-07-25 19:32:16

写吧

ProcessStartInfo psi= new ProcessStartInfo("cmd.exe");
......

psi.CreateNoWindow = true;

Just write

ProcessStartInfo psi= new ProcessStartInfo("cmd.exe");
......

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