GUI 和命令行的 C# 应用程序

标签 c# winforms user-interface command-line

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

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

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

最佳答案

  1. 编辑您的项目属性,使您的应用程序成为“Windows 应用程序”(而非“控制台应用程序”)。您仍然可以通过这种方式接受命令行参数。如果您不这样做,那么当您双击该应用程序的图标时,将弹出一个控制台窗口。
  2. 确保您的 Main 函数接受命令行参数。
  3. 如果您获得任何命令行参数,请不要显示该窗口。

这是一个简短的例子:

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

如果您的应用程序尚未构建为干净地执行静默处理(如果您的所有逻辑都塞进了您的 WinForm 代码),您可以 hack silent processing in ala CharithJ's answer .

由 OP 编辑​​ 很抱歉劫持你的答案梅林。只想在这里为其他人提供所有信息。

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

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

关于GUI 和命令行的 C# 应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7198639/

相关文章:

c# - 在多个屏幕上显示相同的网页

iphone - 关于创建 iPhone Piano UI 的问题

登录失败时生成 Python PXSSH GUI

c# - 我可以在保存更改之前验证实体吗?

c# - 无法将类型为 'System.String' 的对象转换为类型 'System.Collections.Hashtable'

c# - .Net 泛型——从接口(interface)实现继承

c# - 组行上的 DevExpress GridHitInfo

c# - 如何在 Xamarin.iOS/Mono 的任务中捕获异常?

c# - 在 Windows 窗体中在鼠标悬停时显示图像?

Java 在可运行 Jar 文件的内容之间来回移动