How to hide a console application in C#

前端 未结 9 1850
刺人心
刺人心 2020-12-06 09:27

I have a console application in C#, and I want that the user won\'t be able to see it.

How can I do that?

相关标签:
9条回答
  • 2020-12-06 10:19

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

    0 讨论(0)
  • 2020-12-06 10:21

    To hide a console applicatin in C# when nothing else works use this code:

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

    Place FreeConsole() anywhere in the code, I placed it in the Init(), and the commandline is hidden.

    0 讨论(0)
  • 2020-12-06 10:22

    Sounds like you don't want a console application, but a windows GUI application that doesn't open a (visible) window.

    0 讨论(0)
提交回复
热议问题