Sponsored Ad

Wednesday, November 25, 2009

C# Bugs Clipboard

Copying text to clipboard

The Clipboard.SetText lets you send text messages to the clipboard for easy control. However, it does not always work as expected. Take for example the following request: clip_image001

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.

clip_image002

When The text of the textbox is correctly initialized , but the RTF text box is all on one line. Depending on your text editor can 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.

clip_image003

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

clip_image004

0 comments:

Post a Comment

Sponsored Ad

More Related Articles

Website Update

Followers