如何隐藏控制台窗口?控制台、窗口

2023-09-02 01:42:35 作者:白衣牛仔少年

问:我有一个不应该被看作一个控制台程序。 (它重置IIS和删除临时文件。)

Question: I have a console program that shouldn't be seen. (It resets IIS and deletes temp files.)

现在我可以设法隐藏窗口开始像这样之后:

Right now I can manage to hide the window right after start like this:

static void Main(string[] args)
{
    var currentProcess = System.Diagnostics.Process.GetCurrentProcess();
    Console.WriteLine(currentProcess.MainWindowTitle);

    IntPtr hWnd = currentProcess.MainWindowHandle;//FindWindow(null, "Your console windows caption"); //put your console window caption here
    if (hWnd != IntPtr.Zero)
    {
        //Hide the window
        ShowWindow(hWnd, 0); // 0 = SW_HIDE
    }

问题是这样的示出了用于第二的眨眼的窗口。 有没有构造一个控制台程序,在那里我可以隐藏窗口,它显示之前?

The problem is this shows the window for a blink of a second. Is there any constructor for a console program, where I can hide the window before it is shown?

其次:

我用

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

和我不喜欢它的32。有没有办法做到这一点没有的DllImport? .NET程序的方式?

and I don't like the 32 in it. Is there any way to do this without DllImport ? A .NET way ?

推荐答案

如果您不需要控制台(如 Console.WriteLine ),然后改变应用程序构建选项​​是一个Windows应用程序。

If you don't need the console (e.g. for Console.WriteLine) then change the applications build options to be a Windows application.

这改变了的.exe 头一个标志,因此Windows不分配一个控制台会话时,应用程序启动。

This changes a flag in the .exe header so Windows doesn't allocate a console session when the application starts.