gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 03:53:18 25 4
gpt4 key购买 nike

我目前有一个带有 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com