用C#隐藏窗口

问题描述

我将C#程序编译为exe文件。当我双击Windows资源管理器中的exe文件时,该程序随黑色命令行窗口一起启动。如何在不显示命令行窗口的情况下从Windows资源管理器启动该文件

[DllImport("user32.dll",CharSet = CharSet.Auto,SetLastError = true)]
    
    private static extern bool ShowWindow(IntPtr hWnd,int nCmdshow);
    private const int HIDE = 0;
    private const int MAXIMIZE = 3;
    private const int MINIMIZE = 6;
    private const int RESTORE = 9;
    
    Process cmd = new Process();
    cmd.StartInfo.FileName = Path.Combine(path,"Launcher.exe");
    cmd.StartInfo.RedirectStandardInput = true;
    cmd.StartInfo.CreateNowindow = true;
    cmd.StartInfo.UseShellExecute = false;
    cmd.Start();
    cmd.StandardInput.WriteLine(argHandlerArgs);
    cmd.StandardInput.Flush();
    cmd.StandardInput.Close();
    
    ShowWindow(cmd.MainWindowHandle,0);

解决方法

如果您要使用的是Windows窗体,则在项目属性中将输出类型设置为Windows应用程序

enter image description here

,

您可以使用ShowWindowApi隐藏命令行。

这是一个例子

using System.Runtime.InteropServices

class CommandLine
{

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

    [DllImport("Kernel32")]
    private static extern IntPtr GetConsoleWindow();

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

    static void Main(string[] args)
    {
         IntPtr hwnd;
         hwnd=GetConsoleWindow();
         ShowWindow(hwnd,SW_HIDE);
    }
}