IT

콘솔이 숨겨진 상태에서 C # 콘솔 응용 프로그램을 실행하는 방법

lottoking 2020. 6. 26. 07:49
반응형

콘솔이 숨겨진 상태에서 C # 콘솔 응용 프로그램을 실행하는 방법


콘솔 응용 프로그램을 실행할 때 콘솔 창을 숨기는 방법이 있습니까?

현재 Windows Forms 응용 프로그램을 사용하여 콘솔 프로세스를 시작하고 있지만 작업이 실행되는 동안 콘솔 창이 표시되는 것을 원하지 않습니다.


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

콘솔 응용 프로그램을 작성한 경우 기본적으로 숨길 수 있습니다.

새 콘솔 앱을 만든 다음 "출력 유형"유형을 "Windows 응용 프로그램"(프로젝트 속성에서 완료)으로 변경하십시오.


Process Class를 사용하는 경우 다음을 작성할 수 있습니다.

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

전에 yourprocess.start();프로세스가 숨겨집니다


콘솔 응용 프로그램의 속성 (프로젝트 속성)으로 이동하십시오. "응용 프로그램"탭에서 "출력 유형"을 "Windows 응용 프로그램"으로 변경하십시오. 그게 다야.


FreeConsole API를 사용 하여 프로세스에서 콘솔을 분리 할 수 있습니다 .

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

(물론 이것은 콘솔 응용 프로그램의 소스 코드에 액세스 할 수있는 경우에만 적용 가능합니다)


출력에 관심이 있다면이 기능을 사용할 수 있습니다.

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

주어진 명령 행 프로그램을 실행하고 완료 될 때까지 기다렸다가 출력을 문자열로 리턴합니다.


사용자 입력이 필요없는 프로그램을 만드는 경우 항상 서비스로 만들 수 있습니다. 서비스에는 어떤 종류의 UI도 표시되지 않습니다.


나는 당신이 원하는 것에 정확히 대답하지는 않는다는 것을 알고 있지만, 당신이 올바른 질문을하고 있는지 궁금합니다.

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.


Add this to your class to import the DLL file:

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

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

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

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


Just write

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

psi.CreateNoWindow = true;

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.

참고URL : https://stackoverflow.com/questions/836427/how-to-run-a-c-sharp-console-application-with-the-console-hidden

반응형