簡體   English   中英

.NET應用程序作為Windows窗體或控制台應用程序運行

[英].NET app running as either Windows Form or as Console Application

我希望從命令行以編程方式運行我的一個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! string只是實際邏輯的占位符。

現在,當從Visual Studio中運行它(使用命令行參數)時,短語It works! 打印到輸出。 但是,當運行/bin/Debug/Program.exe文件(或/ Release)時,應用程序崩潰。

我是以正確的方式來做這件事的嗎? 讓我的邏輯類成為由兩個獨立應用程序加載的DLL會更有意義(即花費更少的開發人員時間)嗎? 還是有一些我不知道的完全不同的東西?

提前致謝!

如果檢測到命令行參數,則需要P / Invoke AllocConsole()。 此主題中檢查我的答案以獲取所需的代碼。 AC#樣本位於頁面下方。 在這里重復,因為我不相信那個糟糕的論壇網站:

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();
  }
}

轉到項目屬性

在“ 應用程序”選項卡上,您應看到名為“ 輸出類型”的下拉列表。 將其更改為Console Application

在那里,你有一個窗口和一個控制台。 現在你的帶有命令參數的代碼應該可行。

是的,最好制作兩個前端.exes(一個用於命令行,一個用於窗口)。

主要原因是您必須為項目指定輸出類型(命令行或Windows應用程序,您不能同時選擇它們。

因此,您必須始終使用Windows應用程序輸出類型(這是Windows消息傳遞系統的開銷,並沒有為您提供“真正的”命令行)。

不確定它是否有所作為,而不是

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

你可以改為

static void Main(string[] args)
{

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM