CloudBuilder.Topshelf/Utility/ConsoleHelper.cs
owenchen 871de41ba5 ow
2026-06-04 08:16:49 +08:00

83 lines
2.8 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
namespace CloudBuilder.Topshelf.Utility
{
// 先把这个类放到你的代码文件里
public static class ConsoleHelper
{
[DllImport("kernel32.dll")]
static extern IntPtr GetStdHandle(int nStdHandle);
[DllImport("kernel32.dll")]
static extern int SetStdHandle(int nStdHandle, IntPtr hHandle);
const int STD_OUTPUT_HANDLE = -11;
const int STD_ERROR_HANDLE = -12;
/// <summary>
/// 屏蔽所有底层C++输出(彻底隐藏 SherpaOnnx 日志)
/// </summary>
public static void DisableConsoleOutput()
{
var nullHandle = IntPtr.Zero;
SetStdHandle(STD_OUTPUT_HANDLE, nullHandle);
SetStdHandle(STD_ERROR_HANDLE, nullHandle);
}
/// <summary>
/// 恢复输出(如果你需要)
/// </summary>
public static void EnableConsoleOutput()
{
var outHandle = GetStdHandle(STD_OUTPUT_HANDLE);
var errHandle = GetStdHandle(STD_ERROR_HANDLE);
SetStdHandle(STD_OUTPUT_HANDLE, outHandle);
SetStdHandle(STD_ERROR_HANDLE, errHandle);
}
}
public static class ConsoleOutput
{
private const int STD_ERROR_HANDLE = -12;
private static IntPtr _originalErrorHandle;
[DllImport("kernel32.dll")]
private static extern IntPtr GetStdHandle(int nStdHandle);
[DllImport("kernel32.dll")]
private static extern bool SetStdHandle(int nStdHandle, IntPtr hHandle);
/// <summary>
/// 只关闭 标准错误输出(stderr)
/// 作用:屏蔽 sherpa-onnx 所有垃圾日志
/// 保留:你的进度条、控制台输出(stdout)
/// </summary>
public static void HideStdError()
{
_originalErrorHandle = GetStdHandle(STD_ERROR_HANDLE);
SetStdHandle(STD_ERROR_HANDLE, IntPtr.Zero);
}
public static void UpdateProgress(int processed, int total)
{
double progressPercent = (double)processed / total * 100;
int progressBarLength = 50; // 进度条总长度
int filledLength = (int)(progressPercent / 100 * progressBarLength);
// 构建进度条(如:[██████████░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░]
string progressBar = "[" + new string('█', filledLength) + new string('░', progressBarLength - filledLength) + "]";
string progressInfo = $"{progressBar} {progressPercent:F2}% | 已处理:{processed}/{total} ";
Console.Write($"\r{progressInfo}");
Console.Out.Flush();
}
}
}