.NET应用程序作为Windows窗体或控制台应用程序运行

时间:2010-05-11 19:47:09

标签: c# winforms console

我希望从命令行以编程方式运行我的一个Windows窗体应用程序。在准备中,我将自己类中的逻辑与Form分开。现在,我不得不尝试让应用程序根据命令行参数的来回来回切换。

以下是主要类的代码:

static class Program
{
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        string[] args = Environment.GetCommandLineArgs();
        if (args.Length > 1) // gets passed its path, by default
        {
            CommandLineWork(args);
            return;
        }         

        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new Form1());
    }

    private static void CommandLineWork(string[] args)
    {
        Console.WriteLine("It works!");
        Console.ReadLine();
    }

其中Form1是我的表单,It works!字符串只是实际逻辑的占位符。

现在,当从Visual Studio中运行此命令(使用命令行参数)时,短语It works!将打印到输出。但是,在运行/bin/Debug/Program.exe文件(或/ Release)时,应用程序崩溃。

我是以正确的方式来做这件事的吗?让我的逻辑类成为由两个独立应用程序加载的DLL会更有意义(即花费更少的开发人员时间)吗?或者是否有一些我不知道的完全不同的东西?

提前致谢!

4 个答案:

答案 0 :(得分:24)

如果检测到命令行参数,则需要P / Invoke AllocConsole()。在this thread中查看我的答案以获取所需的代码。 C#示例位于页面下方。在这里重复,因为我不相信那个糟糕的论坛网站:

using System;
using System.Windows.Forms;

namespace WindowsApplication1 {
  static class Program {
    [STAThread]
    static void Main(string[] args) {
      if (args.Length > 0) {
        // Command line given, display console
        AllocConsole();
        ConsoleMain(args);
      }
      else {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new Form1());
      }
    }
    private static void ConsoleMain(string[] args) {
      Console.WriteLine("Command line = {0}", Environment.CommandLine);
      for (int ix = 0; ix < args.Length; ++ix)
        Console.WriteLine("Argument{0} = {1}", ix + 1, args[ix]);
      Console.ReadLine();
    }

    [System.Runtime.InteropServices.DllImport("kernel32.dll")]
    private static extern bool AllocConsole();
  }
}

答案 1 :(得分:1)

是的,最好制作两个前端.exes(一个用于命令行,一个用于窗口)。

主要原因是你必须为项目指定输出类型(命令行或Windows应用程序,你不能同时选择它们。

因此,您必须始终使用Windows应用程序输出类型(这会导致Windows消息传递系统的开销,并且不会为您提供“真正的”命令行)。

答案 2 :(得分:1)

不确定它是否有所作为,而不是

static void Main()
{
        string[] args = Environment.GetCommandLineArgs();

你可以改为

static void Main(string[] args)
{

答案 3 :(得分:1)

转到项目属性

Application 选项卡上,您会看到一个名为输出类型的下拉列表。将其更改为控制台应用程序

在那里,你有一个窗口和一个控制台。现在你的带有命令参数的代码应该可以工作。