Created
August 5, 2014 16:54
-
-
Save YellowAfterlife/5ad959c31986019e293e to your computer and use it in GitHub Desktop.
A test for clipboard manipulation in C#.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.IO; | |
using System.Windows.Forms; | |
// ^ In a console application project you'll need to add a reference to this first. | |
namespace CSCoTest { | |
class Program { | |
static MemoryStream stringToMemoryStream(string value) { | |
return new MemoryStream(System.Text.Encoding.UTF8.GetBytes(value)); | |
} | |
static string memoryStreamToString(MemoryStream value) { | |
int length = (int)value.Length; | |
byte[] buffer = new byte[length]; | |
value.Read(buffer, 0, length); | |
return System.Text.Encoding.UTF8.GetString(buffer); | |
} | |
[STAThread] | |
static void Main(string[] args) { | |
bool done = false; | |
do { | |
Console.WriteLine("Options:"); | |
Console.WriteLine("C copy"); | |
Console.WriteLine("P paste"); | |
Console.WriteLine("* exit"); | |
Console.Write("> "); | |
ConsoleKeyInfo key = Console.ReadKey(); | |
Console.WriteLine(); | |
IDataObject data; | |
switch (key.KeyChar) { | |
case 'c': | |
data = new DataObject(); | |
data.SetData("Text", "(text)"); | |
data.SetData("Xml", stringToMemoryStream("<xml/>")); | |
Clipboard.SetDataObject(data, true); | |
Console.WriteLine("Copied!"); | |
break; | |
case 'p': | |
data = Clipboard.GetDataObject(); | |
// Read text: | |
Console.Write("Text: "); | |
object text = data.GetData("Text"); | |
if (text == null) { | |
Console.WriteLine("(null)"); | |
} else if (text is string) { | |
Console.WriteLine(text as string); | |
} else { | |
Console.WriteLine("(not a string)"); | |
} | |
// Read bytes: | |
Console.Write("Xml: "); | |
object xml = data.GetData("Xml"); | |
if (xml == null) { | |
Console.WriteLine("(null)"); | |
} else if (xml is MemoryStream) { | |
Console.WriteLine("(stream) " + memoryStreamToString((MemoryStream)xml)); | |
} else if (xml is string) { | |
Console.WriteLine("(string) " + (string)xml); | |
} else { | |
Console.WriteLine("(unknown type)"); | |
} | |
// | |
Console.WriteLine("Pasted!"); | |
break; | |
default: | |
done = true; | |
break; | |
} | |
} while (!done); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment