本文介绍了C# 应用程序 GUI 和命令行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前有一个带有 GUI 的应用程序.

I currently have an application with a GUI.

是否可以从命令行(没有 GUI 和使用参数)使用相同的应用程序.

Would it be possible to use this same application from the commandline (without GUI and with using parameters).

还是我必须为命令行工具创建一个单独的 .exe(和应用程序)?

Or do I have to create a separate .exe (and application) for the commandline tool?

推荐答案

  1. 编辑您的项目属性,使您的应用成为Windows 应用程序"(而不是控制台应用程序").您仍然可以通过这种方式接受命令行参数.如果你不这样做,那么当你双击应用程序的图标时会弹出一个控制台窗口.
  2. 确保您的 Main 函数接受命令行参数.
  3. 如果您获得任何命令行参数,则不要显示该窗口.
  1. Edit your project properties to make your app a "Windows Application" (not "Console Application"). You can still accept command line parameters this way. If you don't do this, then a console window will pop up when you double-click on the app's icon.
  2. Make sure your Main function accepts command line parameters.
  3. Don't show the window if you get any command line parameters.

这是一个简短的例子:

[STAThread]
static void Main(string[] args)
{
    if(args.Length == 0)
    {
        Application.Run(new MyMainForm());
    }
    else
    {
        // Do command line/silent logic here...
    }
}

如果您的应用程序的结构还没有干净地进行静默处理(如果您的所有逻辑都塞进了您的 WinForm 代码中),您可以在 ala CharithJ 的回答中破解静默处理.

If your app isn't already structured to cleanly do silent processing (if all your logic is jammed into your WinForm code), you can hack silent processing in ala CharithJ's answer.

由 OP 编辑​​很抱歉劫持了您的回答 Merlyn.只想为其他人提供这里的所有信息.

EDIT by OPSorry to hijack your answer Merlyn. Just want all the info here for others.

要能够在 WinForms 应用程序中写入控制台,只需执行以下操作:

To be able to write to console in a WinForms app just do the following:

static class Program
{
    // defines for commandline output
    [DllImport("kernel32.dll")]
    static extern bool AttachConsole(int dwProcessId);
    private const int ATTACH_PARENT_PROCESS = -1;

    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main(string[] args)
    {
        // redirect console output to parent process;
        // must be before any calls to Console.WriteLine()
        AttachConsole(ATTACH_PARENT_PROCESS);

        if (args.Length > 0)
        {
            Console.WriteLine("Yay! I have just created a commandline tool.");
            // sending the enter key is not really needed, but otherwise the user thinks the app is still running by looking at the commandline. The enter key takes care of displaying the prompt again.
            System.Windows.Forms.SendKeys.SendWait("{ENTER}");
            Application.Exit();
        }
        else
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new QrCodeSampleApp());
        }
    }
}

这篇关于C# 应用程序 GUI 和命令行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 05:39