I’ve build a console application that has a command interpreter. To make things easier I needed to add support for reading the clipboard when ctrl+v is pressed. When I press ctrl+v I see the symbol ^V in the console, so I’m replacing that character with the clipboard text. After some googling I’ve found out that the clipboard can be accessed by System.Windows.Forms.Clipboard.GetText().
My question is: Is there a better solution to add clipboard support to a console application? Possibly without using System.Windows.Forms.Clipboard? Maybe an interop call can do the trick?
One of the drawbacks of this solution is that the clipboard only works when the thread is defined as [STAThread]. It would also be a lot nicer if I could get rid of the ^V symbol.
This is the code of the current solution:
using System;
using System.Threading;
using System.Windows.Forms;
namespace ConsoleApplication1
{
class Program
{
public static readonly string ClipboardChar = Convert.ToChar(22).ToString();
[STAThread]
static void Main(string[] args)
{
Console.Write("Do some pastin': ");
//read
Console.ForegroundColor = ConsoleColor.White;
string result = Console.ReadLine();
Console.ResetColor();
//read keyboard
if (result.Contains(ClipboardChar))
{
result = result.Replace(ClipboardChar, Clipboard.GetText());
}
//write result
Console.WriteLine("\nResult: ");
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine(result);
Console.ResetColor();
Console.WriteLine("\nPress any key to continue...");
Console.ReadKey();
}
}
}