我有一个 C# 控制台应用程序项目,其中输出类型设置为“Windows 应用程序”。这样控制台就不会在程序启动时闪烁。
但是我也想允许一个帮助命令行参数,如果您使用“/?”从命令行运行程序,它将显示有关程序的详细信息。作为一个论点。
有没有办法让程序作为 Windows 应用程序正常运行,但如果传递帮助参数则显示控制台?
编辑 - 阅读答案和 This question 上的类似答案后(这个问题假设您正在使用控制台应用程序输出类型运行)我正在使用这个解决方案。
[DllImport(Kernel32_DllName)]
private static extern bool AllocConsole();
[DllImport("kernel32.dll")]
static extern IntPtr GetConsoleWindow();
[DllImport("user32.dll")]
static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
const int SW_HIDE = 0;
const int SW_SHOW = 5;
static void Main(string[] args)
{
if(args.Contains("/?"))
{
AllocConsole();
Console.WriteLine("helpText");
Console.ReadLine();
var handle = GetConsoleWindow();
//Hides console
ShowWindow(handle, SW_HIDE);
}
}
最佳答案
我还没有找到一种方法可以完全按照您的要求进行操作,但是您可以根据输入打开控制台。例如:
class Program
{
private const string Kernel32_DllName = "kernel32.dll";
[DllImport(Kernel32_DllName)]
private static extern bool AllocConsole();
static void Main(string[] args)
{
if (args[0] == "/")
{
AllocConsole();
Console.WriteLine("Details");
Console.ReadKey();
//cases and such for your menu options
}
即使项目的输出类型是 Windows 应用程序,如果您使用带有/的运行命令,也会打开一个控制台,您可以使用该控制台。
关于c# - 如何在具有 Windows 应用程序输出类型的 C# 程序上显示控制台,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23409970/