玩过单机游戏的人都应该有这种体会:按下一个特定按键,游戏便弹出一个类似dos的窗口,然后输入相关信息就可以改变游戏内容,大多数单机游戏都支持这种合法的作弊方式。
个人在开发form程序的时候,有时候会在后台用非界面线程处理一些耗时操作,有时希望能看到中间的一些调试信息,但是如果使用form输出,就会很麻烦,涉及到线程同步问题,而且有时候有些信息仅仅是为了给开发人员看的,这个时候便想到调用一个控制台输出就方便且直白,在网上找了一些方案,现在一一说明:
1.调用api,和调用其他的win api没什么差别
public class ConsoleHelper
{
public static int Create()
{
if (AllocConsole())
return 0;
else
return Marshal.GetLastWin32Error();
}
public static int Destroy()
{
if (FreeConsole())
return 0;
else
return Marshal.GetLastWin32Error();
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressUnmanagedCodeSecurity]
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool AllocConsole();
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressUnmanagedCodeSecurity]
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool FreeConsole();
}
这样就可以利用console.write()来向控制台输出,而不必要考虑线程同步的问题,这样相比于写到文本更实时直观。