Boppity Bop
Boppity Bop

Reputation: 10463

C#. How to programmatically select and copy text from the console application?

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).

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

C# 3.5 / 4

Upvotes: 8

Views: 6477

Answers (2)

ChristopheD
ChristopheD

Reputation: 116117

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)
    }
}

Upvotes: 6

&#214;rjan J&#228;mte
&#214;rjan J&#228;mte

Reputation: 14757

This will give the stdout to the clipboard.

dir | clip

Where dir is just my test command...

Upvotes: 2

Related Questions