89 lines
2.8 KiB
C#
89 lines
2.8 KiB
C#
using System;
|
|
using System.IO;
|
|
using System.Runtime.InteropServices;
|
|
|
|
namespace ClassLibrary1
|
|
{
|
|
static class ConsoleShow
|
|
{
|
|
static bool bFlag = false;
|
|
public static void Log(string str)
|
|
{
|
|
if (!bFlag)
|
|
{
|
|
bFlag = true;
|
|
AllocConsole();
|
|
// stdout's handle seems to always be equal to 7
|
|
IntPtr defaultStdout = new IntPtr(7);
|
|
IntPtr currentStdout = GetStdHandle(StdOutputHandle);
|
|
|
|
if (currentStdout != defaultStdout)
|
|
// reset stdout
|
|
SetStdHandle(StdOutputHandle, defaultStdout);
|
|
|
|
// reopen stdout
|
|
TextWriter writer = new StreamWriter(Console.OpenStandardOutput())
|
|
{ AutoFlush = true };
|
|
Console.SetOut(writer);
|
|
}
|
|
WriteLine(str);
|
|
|
|
FileLog.Log(str);
|
|
}
|
|
/// <summary>
|
|
/// 启动控制台
|
|
/// </summary>
|
|
/// <returns></returns>
|
|
[DllImport("kernel32.dll")]
|
|
public static extern bool AllocConsole();
|
|
|
|
/// <summary>
|
|
/// 释放控制台
|
|
/// </summary>
|
|
/// <returns></returns>
|
|
[DllImport("kernel32.dll")]
|
|
public static extern bool FreeConsole();
|
|
|
|
// P/Invoke required:
|
|
private const UInt32 StdOutputHandle = 0xFFFFFFF5;
|
|
[DllImport("kernel32.dll")]
|
|
private static extern IntPtr GetStdHandle(UInt32 nStdHandle);
|
|
[DllImport("kernel32.dll")]
|
|
private static extern void SetStdHandle(UInt32 nStdHandle, IntPtr handle);
|
|
|
|
|
|
/// <summary>
|
|
/// 输出信息
|
|
/// </summary>
|
|
/// <param name="format"></param>
|
|
/// <param name="args"></param>
|
|
public static void WriteLine(string format, params object[] args)
|
|
{
|
|
WriteLine(string.Format(format, args));
|
|
}
|
|
|
|
/// <summary>
|
|
/// 输出信息
|
|
/// </summary>
|
|
/// <param name="output"></param>
|
|
public static void WriteLine(string output)
|
|
{
|
|
Console.ForegroundColor = GetConsoleColor(output);
|
|
Console.WriteLine(@"[{0}]{1}", DateTimeOffset.Now, output);
|
|
}
|
|
|
|
/// <summary>
|
|
/// 根据输出文本选择控制台文字颜色
|
|
/// </summary>
|
|
/// <param name="output"></param>
|
|
/// <returns></returns>
|
|
private static ConsoleColor GetConsoleColor(string output)
|
|
{
|
|
if (output.StartsWith("警告")) return ConsoleColor.Yellow;
|
|
if (output.StartsWith("错误")) return ConsoleColor.Red;
|
|
if (output.StartsWith("注意")) return ConsoleColor.Green;
|
|
return ConsoleColor.Gray;
|
|
}
|
|
}
|
|
}
|