0

当我的应用程序试图在控制台上写东西时,我需要捕获事件。

Console.WriteLine("Any text");

是否可以在事件或方法中将文本发送到控制台输出?

4

3 回答 3

1

一种方法是创建一个新的流覆盖,如本文所示:

http://mel-green.com/2010/01/progressstream/

然后,您需要将其设置为控制台写入的流,例如

MemoryStream ms = new MemoryStream();
ProgressStream progressStream = new ProgressStream(ms);
Console.SetOut(new StreamWriter(progressStream));

然后使用进度流的事件来查看它何时被写入。

于 2012-11-06T10:20:31.360 回答
0

这可能对您有帮助:

using System;
using System.IO;

namespace nsStreams
{
    public class Redirect
    {
        static public void Main ()
        {
            FileStream ostrm;
            StreamWriter writer;
            TextWriter oldOut = Console.Out;
            try
            {
                ostrm = new FileStream ("./Target.txt", FileMode.OpenOrCreate, FileAccess.Write);
                writer = new StreamWriter (ostrm);
            }
            catch (Exception e)
            {
                Console.WriteLine (e.Message);
                return;
            }
            Console.SetOut (writer);

            Console.SetOut (oldOut);
            writer.Close();
            ostrm.Close();
            Console.WriteLine ("Done");
        }
    }
}
于 2012-11-06T10:24:20.670 回答
0

这是我用来为控制台内容创建线程安全侦听器的示例,我们将其“打印”到 WPF 元素绑定到的可观察集合中。

创建一个自定义 TextWriter 类,以便您可以挂钩该过程:

public class CustomTextWriter : TextWriter
{
    private readonly StringBuilder lineBuffer = new();

    public event EventHandler<StringEventArgs>? LogModelReadyToAdd;

    public override Encoding Encoding => Encoding.UTF8;

    public override void Write(char value)
    {
        // This is the inner-most write, as it is down to a single character
        if (value is '\r' or '\n')
        {
            if (lineBuffer.Length > 0)
            {
                LogModelReadyToAdd?.Invoke(
                    this,
                    new(lineBuffer.ToString()));
                lineBuffer.Clear();
            }
            return;
        }
        lineBuffer.Append(value);
    }
}

使用快速字符串事件 args 对象:

public class StringEventArgs : EventArgs
{
    public StringEventArgs()
    {
    }

    public StringEventArgs(string @string)
    {
        String = @string;
    }

    public string? String { get; init; }
}

在我的主窗口中(上下文是我要绑定的,我的 OnInitialized 中有这个):

CustomTextWriter writer = new();
writer.LogModelReadyToAdd += async (_, args) =>
{
    if (Application.Current.CheckAccess())
    {
        TheContext.StepLog?.Add(new() { Log = args.String, });
        return;
    }
    await Application.Current.Dispatcher.BeginInvoke(
        DispatcherPriority.Background,
        new Action(() => TheContext.StepLog?.Add(new() { Log = args.String, })));
};
Console.SetOut(writer);
于 2021-12-15T04:10:51.983 回答