如何创建一个C#应用程序,自行决定是否显示为一个控制台或窗口的应用程序? [英] How do I create a C# app that decides itself whether to show as a console or windowed app?

查看:177
本文介绍了如何创建一个C#应用程序,自行决定是否显示为一个控制台或窗口的应用程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法来启动一个C#应用程序,具有以下特点?

Is there a way to launch a C# application with the following features?

  1. 在它决定通过命令行参数,无论是窗口或控制台应用程序
  2. 它不显示控制台当要求被加窗并且当从控制台运行不显示一个GUI窗口。

例如,

myapp.exe /help

将输出到标准输出,你所用的控制台上,但

would output to stdout on the console you used, but

myapp.exe

本身将推出我的WinForms或WPF用户界面。

我知道最好的答案为止涉及具有两个独立的exe文件,并使用IPC,但感觉真的哈克。

by itself would launch my Winforms or WPF user interface.

The best answers I know of so far involve having two separate exe and use IPC, but that feels really hacky.


我有什么选择和权衡我可以得到在上面的例子中描述的行为?我很开放的想法,是WinForm的专用或WPF特有的了。


What options do I have and trade-offs can I make to get the behavior described in the example above? I'm open to ideas that are Winform-specific or WPF-specific, too.

推荐答案

请在应用常规的Windows应用程序,并在需要时动态创建一个控制台。

Make the app a regular windows app, and create a console on the fly if needed.

更多详情请见<一href="http://social.msdn.microsoft.com/Forums/en-US/Vsex$p$pssvb/thread/875952fc-cd2c-4e74-9cf2-d38910bde613">this链接($ C $从那里低于C)

More details at this link (code below from there)

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#应用程序,自行决定是否显示为一个控制台或窗口的应用程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆