控制台应用程序也可以作为GUI运行

时间:2015-08-11 11:04:00

标签: c# .net console-application windows-applications

  

之前有人将此标记为重复,请阅读

我有一个Windows Application的进程,用C#编写。

Image showing project Properties

现在我有一个要求,我也希望从控制台运行它。像这样。

enter image description here

由于我需要向控制台显示输出,因此我将应用程序类型更改为Console Application

enter image description here

现在的问题是,每当用户从Windows资源管理器启动一个进程时(通过加倍点击)。控制台窗口也会在后面打开。

enter image description here

有没有办法避免这种情况?

在@ PatrickHofman的帮助下我尝试了什么。

但我仍有问题

1 个答案:

答案 0 :(得分:3)

好吧,我以为我很好奇,因为我很好奇。

  • 首先,我更新了Main中的Program.cs方法以获取参数,以便我可以指定-cli并让应用程序在命令行上运行。
  • 其次,我将项目的输出类型更改为"控制台应用程序"在项目属性中。
  • 第三,我将以下方法添加到Program.cs

    private static void HideConsoleWindow()
    {
        var handle = GetConsoleWindow();
    
        ShowWindow(handle, 0);
    }
    
    [DllImport("kernel32.dll")]
    static extern IntPtr GetConsoleWindow();
    
    [DllImport("user32.dll")]
    static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
    
  • 第四,我将HideConsoleWindow称为非CLI模式下的第一个操作。

完成这些步骤后,我的(基本)应用程序如下所示:

    [STAThread]
    static void Main(string[] args)
    {
        if (args.Any() && args[0] == "-cli")
        {
            Console.WriteLine("Console app");
        }
        else
        {
            HideConsoleWindow();
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }
    }

然后,如果我使用-cli开关在命令行上打开程序,它将作为命令行应用程序运行并将内容打印到命令行,如果我正常运行它会加载命令行窗口(非常)简单地然后加载为您期望的正常应用程序。