通过调用系统API实现打开和关闭控制台:
// 启动控制台
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
public static extern bool AllocConsole();
// 释放控制台
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
public static extern bool FreeConsole();
如果你需要实现禁用控制台右上角的关闭按钮(如果直接使用关闭按钮“X”关闭控制台,会导致整个程序退出),还需要调用API:
[DllImport("Kernel32.dll", CharSet = CharSet.Auto)]
private static extern IntPtr GetConsoleWindow();
[DllImport("user32.dll", CharSet = CharSet.Auto)]
private static extern IntPtr GetSystemMenu(IntPtr hWnd, IntPtr bRevert);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
private static extern IntPtr RemoveMenu(IntPtr hMenu, uint uPosition, uint uFlags);
1. 打开控制台
public static bool OpenConsole()
{
return AllocConsole();
}
如果需要禁用关闭按钮:
public static bool OpenConsole()
{
bool flag = AllocConsole();
if (flag)
{
//禁用关闭按钮
IntPtr windowHandle = GetConsoleWindow();
IntPtr closeMenu = GetSystemMenu(windowHandle, IntPtr.Zero);
const uint SC_CLOSE = 0xF060;
RemoveMenu(closeMenu, SC_CLOSE, 0x0);
}
return flag;
}
2. 关闭控制台
public static bool CloseConsole()
{
return FreeConsole();
}
3. 在控制台中输出
Console.WriteLine("hello world");
如果需要改变输出文字的颜色(默认颜色为灰色):
ConsoleShell.WriteLine("hello world", ConsoleColor.Red);
可以直接定义一个函数用来输出,在函数中可以规定输出的格式、颜色等,如:(每次输出时,都在前面添加当前时间)
public void write(string text, ConsoleColor textColor)
{
Console.ForegroundColor = textColor;
Console.WriteLine(@"[{0}] {1}", DateTimeOffset.Now, text);
}