c# - 如何创建一个 C# 应用程序来决定是显示为控制台应用程序还是窗口应用程序?

标签 c# .net wpf winforms

有没有办法启动具有以下功能的 C# 应用程序?

  1. 通过命令行参数判断是窗口应用还是控制台应用
  2. 它在被要求打开窗口时不显示控制台,并且在从控制台运行时不显示 GUI 窗口。

例如,

myapp.exe /help
将在您使用的控制台上输出到标准输出,但是
myapp.exe
本身会启动我的 Winforms 或 WPF 用户界面。

到目前为止,我所知道的最佳答案涉及拥有两个独立的 exe 并使用 IPC,但这感觉真的很糟糕。


我有哪些选择和权衡取舍才能获得上述示例中描述的行为?我也愿意接受特定于 Winform 或特定于 WPF 的想法。

最佳答案

使该应用程序成为常规 Windows 应用程序,并在需要时即时创建控制台。

更多详情请访问 this link (下面的代码)

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
        if ( !AttachConsole(-1) ) { // Attach to an parent process console
           AllocConsole(); // Alloc a new console
        }

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

    [System.Runtime.InteropServices.DllImport("kernel32.dll")]
    private static extern bool AttachConsole(int pid);

  }
}

关于c# - 如何创建一个 C# 应用程序来决定是显示为控制台应用程序还是窗口应用程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/807998/

相关文章:

java - 尝试使用java中的资源和异常

c# ZipFile.CreateFromDirectory - 进程无法访问文件 "path_to_the_zip_file_created.zip",因为它正被另一个进程使用

.net - Keyboard.FocusedElement为空,可能的原因是什么?

c# - 使用 JSON.NET 在 C# 中将部分 json 反序列化为数据表

c# - 使用 NUnit 模拟 EF 的 ExecuteSqlCommand

c# - JIT 后的 .NET 代码是否与 native 代码一样执行

.net - 创建类型结构的属性 - 错误

c# - WPF 中的图像处理不是线程安全的?

c# - WPF 窗口最大化导致项目错位

c# - MVcHtmlString 中的堆栈溢出异常