在wpf項目下創建一個類文件 代碼如下:
using System;
using System.Runtime.InteropServices;
namespace xxxxxxx
{
public class ConsoleLogHelper
{
[System.Security.SuppressUnmanagedCodeSecurity]
[DllImport("kernel32", CharSet = CharSet.Auto)]
internal static extern bool AllocConsole();
[System.Security.SuppressUnmanagedCodeSecurity]
[DllImport("kernel32", CharSet = CharSet.Auto)]
internal static extern bool FreeConsole();
/// <summary>
/// 在程序啓動時,執行一次即可
/// </summary>
public static void OpenConsole()
{
try
{
var consoleTitle = "App Runtime Log";
AllocConsole();
Console.BackgroundColor = ConsoleColor.Black;
Console.CursorVisible = false;
Console.Title = consoleTitle;
}
catch (Exception)
{
throw;
}
}
/// <summary>
/// 該方法只在退出程序時,調用
/// </summary>
public static void CloseConsole()
{
FreeConsole();
}
public static void WriteLine(string msg, ConsoleColor color=ConsoleColor.White)
{
Console.ForegroundColor = color;
Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
Console.WriteLine(msg);
}
public static void WriteLineError(string msg)
{
Console.ForegroundColor = ConsoleColor.Red;
WriteLine(msg);
}
public static void WriteLineError(Exception ex)
{
WriteLineError(ex.Message);
}
public static void WriteLineInfo(string msg)
{
WriteLine(msg, ConsoleColor.Cyan);
}
}
}
App.xaml.cs類 啓動關閉
public partial class App : Application
{
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
ConsoleLogHelper.OpenConsole();
}
protected override void OnExit(ExitEventArgs e)
{
base.OnExit(e);
ConsoleLogHelper.CloseConsole();
}
}
ok 可以使用啦
ConsoleLogHelper.WriteLine("Hello World");