Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net

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

like image 240
Boppity Bop Avatar asked Nov 27 '10 16:11

Boppity Bop


2 Answers

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)
    }
}
like image 126
ChristopheD Avatar answered Oct 18 '22 13:10

ChristopheD


This will give the stdout to the clipboard.

dir | clip

Where dir is just my test command...

like image 39
Örjan Jämte Avatar answered Oct 18 '22 12:10

Örjan Jämte