表单应用程序-输出到命令提示符而不创建额外的控制台
本文关键字:创建 控制台 应用程序 输出 命令提示符 表单 | 更新日期: 2023-09-27 18:03:27
我有一个奇怪的问题。
我已经创建了一个表单应用程序,有菜单,选项,按钮等。此外,我还实现了使用参数和从命令提示符启动应用程序来打开和关闭某些选项的可能性。现在我想实现对额外的"帮助"参数的反应,我希望它显示有关所有可能的参数和一些示例的信息。是否有办法显示一些输出控制台,我目前正在运行,而不创建额外的控制台?或者直接显示带有所有参数描述的新MessageBox会更简单?
谢谢!
如果没有重要的原因,你会使用控制台-我只会使用MessageBox
混合控制台和windows窗体不是一个好主意。
如果你真的必须这样做-在kernel32.dll
中有AttachConsole功能。你可以这样使用:
Program.cs文件:
using System;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace Test
{
static class Program
{
[DllImport("kernel32.dll")]
static extern bool AttachConsole(int dwProcessId);
private const int ATTACH_PARENT_PROCESS = -1;
[STAThread]
static void Main()
{
AttachConsole(ATTACH_PARENT_PROCESS);
Console.WriteLine("This will show on console.");
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
当我需要它时,我使用它将控制台添加到应用程序中:
#region Console support
[System.Runtime.InteropServices.DllImport("Kernel32")]
public static extern void AllocConsole();
[System.Runtime.InteropServices.DllImport("Kernel32")]
public static extern void FreeConsole();
#endregion
当我们需要打开它时,我们可以调用AllocConsole()
,同样地,当我们想关闭它时,我们可以调用FreeConsole()
。
同样,我创建/使用下面的代码用颜色写入控制台:
/// <summary>
/// Writes to the Console. Does not terminate line, subsequent write is on right of same line.
/// </summary>
/// <param name="color">The color that you want to write to the line with.</param>
/// <param name="text">The text that you want to write to the console.</param>
public static void ColoredConsoleWrite(ConsoleColor color, string text)
{
ConsoleColor originalColor = Console.ForegroundColor;
Console.ForegroundColor = color;
Console.Write(text);
Console.ForegroundColor = originalColor;
}
/// <summary>
/// Writes to the Console. Terminates line, subsequent write goes to new line.
/// </summary>
/// <param name="color">The color that you want to write to the line with.</param>
/// <param name="text">The text that you want to write to the console.</param>
public static void ColoredConsoleWriteLine(ConsoleColor color, string text)
{
ConsoleColor originalColor = Console.ForegroundColor;
Console.ForegroundColor = color;
Console.WriteLine(text);
Console.ForegroundColor = originalColor;
}
使用例子:
#region User Check
Console.Write("User: {0} ... ", Environment.UserName);
if (validUser(Environment.UserName).Equals(false))
{
ColoredConsoleWrite(ConsoleColor.Red, "BAD!");
Console.WriteLine(" - Making like a tree, and getting out of here!");
Environment.Exit(0);
}
ColoredConsoleWrite(ConsoleColor.Green, "GOOD!"); Console.WriteLine(" - Continue on!");
#endregion
"GOOD!"为绿色的有效用户输出:
User: Chase.Ring ... GOOD! - Continue on!
无效的用户输出,"BAD!"为红色文本:
User: Not.Chase.Ring ... BAD! - Making like a tree, and getting out of here!