gpt4 book ai didi

c# - 控制台应用程序也作为 GUI 运行

转载 作者:可可西里 更新时间:2023-11-01 09:19:55 27 4
gpt4 key购买 nike

Before anyone marks this as Duplicate, Please read

我有一个 Windows Application 进程,它是用 C# 编写的。

Image showing project Properties

现在我有一个要求,我也想从控制台运行它。像这样。

enter image description here

因为我需要向控制台显示输出,所以我将应用程序类型更改为Console Application

enter image description here

现在的问题是,每当用户从 Windows 资源管理器(通过双击)启动进程时。控制台窗口也在后面打开。

enter image description here

有没有办法避免这种情况?

在@PatrickHofman 的帮助下我尝试了什么。

但是我还是有问题

最佳答案

好吧,因为我很好奇,所以我想我可以尝试一下。

  • 首先,我更新了 Program.cs 中的 Main 方法以获取参数,这样我就可以指定 -cli 并让应用程序运行命令行。
  • 其次,我在项目属性中将项目的输出类型更改为“控制台应用程序”。
  • 第三我在Program.cs中添加了以下方法

    private static void HideConsoleWindow()
    {
    var handle = GetConsoleWindow();

    ShowWindow(handle, 0);
    }

    [DllImport("kernel32.dll")]
    static extern IntPtr GetConsoleWindow();

    [DllImport("user32.dll")]
    static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
  • 第四,我调用 HideConsoleWindow 作为非 CLI 模式下的第一个操作。

完成这些步骤后,我的(基本)应用程序如下所示:

    [STAThread]
static void Main(string[] args)
{
if (args.Any() && args[0] == "-cli")
{
Console.WriteLine("Console app");
}
else
{
HideConsoleWindow();
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}

然后,如果我使用 -cli 开关在命令行上打开程序,它会作为命令行应用程序运行并将内容打印到命令行,如果我正常运行它,它会加载命令行窗口(非常)简短,然后像您期望的那样作为普通应用程序加载。

关于c# - 控制台应用程序也作为 GUI 运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31940032/

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