在WPF中打印Console日志的方法
- 创建一个WPF项目
- 新建一个文件Log.cs
- 拷贝如下代码到Log.cs中
- 在初始化相关位置调用Log.CreateConsole()
Log.cs代码
using System;
using System.IO;
using System.Runtime.InteropServices;
public static class Log
{
//WinApi函数
[DllImport("kernel32.dll")]
private static extern Boolean AllocConsole();
[DllImport("kernel32.dll")]
private static extern Boolean FreeConsole();
//输出颜色
private enum MSG_COLOR { GRAY, GREEN, YELLOW, RED };
//多线程锁
private static object m_lock = new object();
//输出重定向
private static FileStream ostrm = null;
private static StreamWriter writer = null;
//创建控制台
public static void CreateConsole()
{
AllocConsole();
}
//销毁控制台
public static void ReleaseConsole()
{
FreeConsole();
}
//重定向到文件
public static void SetOutputFile(string filePath = "./log.txt")
{
ostrm = new FileStream(filePath, FileMode.Create, FileAccess.Write);
writer = new StreamWriter(ostrm);
Console.SetOut(writer);
}
//输出白色消息
public static void Info(string format, params object[] args)
{
WriteMessage(MSG_COLOR.GRAY, format, args);
}
//输出绿色消息
public static void Suc(string format, params object[] args)
{
WriteMessage(MSG_COLOR.GREEN, format, args);
}
//输出黄色消息
public static void Warning(string format, params object[] args)
{
WriteMessage(MSG_COLOR.YELLOW, format, args);
}
//输出红色消息
public static void Error(string format, params object[] args)
{
WriteMessage(MSG_COLOR.RED, format, args);
}
private static void WriteMessage(MSG_COLOR color, string format, params object[] args)
{
lock (m_lock)
{
switch (color)
{
case MSG_COLOR.GRAY:
Console.ForegroundColor = ConsoleColor.Gray;
break;
case MSG_COLOR.GREEN:
Console.ForegroundColor = ConsoleColor.Green;
break;
case MSG_COLOR.YELLOW:
Console.ForegroundColor = ConsoleColor.Yellow;
break;
case MSG_COLOR.RED:
Console.ForegroundColor = ConsoleColor.Red;
break;
default:
Console.ForegroundColor = ConsoleColor.Gray;
break;
}
Console.WriteLine(format, args);
Console.ForegroundColor = ConsoleColor.Gray;
}
}
}