隐藏控制台窗口,来自控制台应用程序。

6
我有一个应用程序,之前使用控制台,但我现在已经将所有的代码更改为写入文件而不是控制台。现在我希望在运行应用程序时停止控制台的出现。我不知道是什么东西首先打开了控制台,即使在代码中没有任何内容被写入它。
我查看了应用程序的引用,但找不到System.Console被引用的地方。我认为禁用它会修复或指向错误的正确方向。我不确定还能在哪里寻找。
所有我在网上找到的其他信息都是关于隐藏控制台的,而我希望它一开始就不要出现。
1个回答

13

进入应用程序属性并将输出类型从控制台应用程序更改为 Windows 应用程序。

或者您可以使用下面的代码来完成。

using System.Runtime.InteropServices;
[DllImport("kernel32.dll")]
static extern IntPtr GetConsoleWindow();

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

在主函数中

const int SW_HIDE = 0;
const int SW_SHOW = 5;
var handle = GetConsoleWindow();

ShowWindow(handle, SW_HIDE); // To hide
ShowWindow(handle, SW_SHOW); // To show

此外,您可以将应用程序作为服务运行。为此,您需要创建一个服务 - 文件->新建项目->Visual C#->Windows->Windows服务。然后创建一个公共方法 StartWork() 并在其中添加所有逻辑。并在 OnStart() 中调用此方法。

 protected override void OnStart(string[] args)
    {
        try
        {
            this.StartJobs();
        }
        catch (Exception ex)
        {
            // catching exception
        }
    }

    public void StartWork()
    {
       // all the logic here
    }

在main函数中,你应该创建这个服务并使用System.ServiceProcess.ServiceBase.Run()来将其作为服务运行,或者调用StartWork()将其作为控制台应用程序运行。

static void Main(string[] args)
{
    TestService = new  TestService ();

    #if DEBUG
        TestService.StartWork()();
    #else
        System.ServiceProcess.ServiceBase.Run(TestService ); 
    #endif
}

这个答案已经被接受为:https://dev59.com/FpLea4cB1Zd3GeqP1V82的答案。 - Metro Smurf

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接