我正在尝试编写一个程序,它可以在控制台或 GUI 模式下运行,具体取决于执行参数。我设法编写了以下示例代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace wfSketchbook
{
static class Program
{
[DllImport("Kernel32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool AttachConsole(int processId);
[DllImport("Kernel32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool AllocConsole();
[DllImport("Kernel32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool FreeConsole();
private const int ATTACH_PARENT_PROCESS = -1;
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
if (args.Length > 0)
{
if (!AttachConsole(ATTACH_PARENT_PROCESS))
AllocConsole();
Console.WriteLine("Welcome to console!");
Console.ReadKey();
FreeConsole();
}
else
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
}
它通常可以工作,但是当从系统命令行调用程序时,cmd 似乎不知道,该程序在控制台模式下工作并立即退出:
d:\Dokumenty\Dev\C#\Projekty\Win32\Sketchbook\wfSketchbook\bin\Debug>wfSketchbook.exe test
d:\Dokumenty\Dev\C#\Projekty\Win32\Sketchbook\wfSketchbook\bin\Debug>Welcome to console!
d:\Dokumenty\Dev\C#\Projekty\Win32\Sketchbook\wfSketchbook\bin\Debug>
我宁愿期待以下输出:
d:\Dokumenty\Dev\C#\Projekty\Win32\Sketchbook\wfSketchbook\bin\Debug>wfSketchbook.exe test
Welcome to console!
d:\Dokumenty\Dev\C#\Projekty\Win32\Sketchbook\wfSketchbook\bin\Debug>
我该如何解决这个问题?
最佳答案
对此没有理想的解决方案。如果 Cmd.exe 可以看到 .exe 是控制台模式应用程序,它只会自动等待程序完成。您的应用程序不会出现这种情况。一种解决方法是让它等待:
start /wait yourapp.exe [arguments]
另一个是始终使用 AllocConsole()。它的副作用是它创建了第二个控制台窗口。将应用程序类型更改为 Console 然后调用 FreeConsole() 也不理想,窗口的闪烁非常明显。选择你的毒药。
关于c# - 如何拥有程序执行时间的控制台?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7058491/