C#。如何以编程方式选择,并从控制台应用程序复制文本?控制台、并从、应用程序、文本

2023-09-03 00:55:24 作者:笑望人非

我想以编程方式复制一个控制台应用程序的整体输出到剪贴板中(这样用户可以自动获得这个没有用CMD窗口修补)。

I want to copy the whole output of a console application programmatically into clipboard (so user can get this automatically without tinkering with cmd window).

我知道如何访问剪贴板。我不知道如何从C#控制台窗口的文本。

I know how to access clipboard. I dont know how to get a console window text from C#.

C#3.5 / 4

C# 3.5 / 4

推荐答案

下面有一个基本的解决方案(只是将标准输出重定向到一个的StringBuilder 实例)。 你可能需要添加引用 System.Windows.Forms的自己在一个控制台应用程序。

One basic solution below (just redirecting standard output to a StringBuilder instance). You probably need to add the reference to System.Windows.Forms yourself in a console application.

using System;
using System.IO;
using System.Text;
using System.Windows.Forms;

public class Redirect
{
    [STAThread()]
    public static void Main()
    {
        StringBuilder sb = new StringBuilder();
        StringWriter sw = new StringWriter(sb);

        Console.SetOut(sw); // redirect

        Console.WriteLine("We are redirecting standard output now...");

        for (int i = 0; i < 10; i++) { Console.WriteLine(i); }

        sw.Close();
        StringReader sr = new StringReader(sb.ToString());
        string completeString = sr.ReadToEnd();
        sr.Close();

        Clipboard.SetText(sb.ToString());
        Console.ReadKey(); // just wait... (press ctrl+v afterwards)
    }
}
 
精彩推荐
图片推荐