C#。如何以编程方式选择,并从控制台应用程序复制文本? [英] C#. How to programmatically select and copy text from the console application?

查看:180
本文介绍了C#。如何以编程方式选择,并从控制台应用程序复制文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想以编程方式复制一个控制台应用程序的整体输出到剪贴板中(这样用户可以自动获得这个没有用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)
    }
}

这篇关于C#。如何以编程方式选择,并从控制台应用程序复制文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆