C# Bugs Clipboard

Microsoft .NET Framework, ASP.NET, Visual C# (CSharp, C Sharp, C-Sharp) Developer Training, Visual Studio


Jump to: navigation, search

Contents

Copying text to clipboard

The Clipboard.SetText allows you to send text to the clipboard very simply. However, it doesn't always work as you would expect. Take for example the following application:

The following source code contains the methods which are called by the corresponding button_Click events.

private void Copy_RTF_TXT()
{
  Clipboard.SetText(richTextBox1.Text);
}
 
private void Copy_TXT()
{
  Clipboard.SetText(textBox1.Text);
}

The Problem

Ctrl + V in a basic text editor (eg notepad) to paste the contents and you'll notice the following.

The text from the textbox is correctly formatted, but the text from the RTF Box is all on one line. Depending on your text editor there may even be null characters.

Hex View

The easiest way to find out what's going on is to load the text file in a binary viewer.

Note that there are two characters after each line from the textbox 0x0D and 0x0A (\r\n). However, only 0x0A (\n) follows the RTF Text lines.

The Solution

The solution is simple, before setting the clipboard text you must insert \r in front of each \n.

The following code shows the updated methods. Note the x++ if inserting a \r to jump past the current and inserted char.

private void Copy_RTF_TXT() 
{
  StringBuilder tempString = new StringBuilder(richTextBox1.Text);
  int x = 0;
 
  do 
  {
    if (tempString[x] == '\n') { tempString.Insert(x++, '\r'); }
  } while (++x < tempString.Length);
 
  Clipboard.SetText(tempString.ToString());
}
 
private void Copy_TXT()
{
  Clipboard.SetText(textBox1.Text);
}


Final Result



Personal tools