0

I have a loop which is appending a new line every time it loops. By the time it finishes, and I copy to clipboard the StringBuilder.ToString() and I paste it in notepad, the blinking cursor remains on a new line below it, instead of at the end of the last string. How can I prevent this from happening and the cursor remaining at the end of the last string, and not below it in a new line?

StringBuilder sbItems = new StringBuilder();
for (int i = 0; i < 10; i++)
{
    sbItems.AppendLine("Item #" + i.ToString());

}
Clipboard.SetText(sbItems.ToString());
Gilad Green
  • 36,708
  • 7
  • 61
  • 95
Michael Weston
  • 377
  • 4
  • 15
  • I couldn't even reproduce the issue with your code tbh. – uTeisT Oct 18 '16 at 06:37
  • Check my answer and tell me if helped you. – mybirthname Oct 18 '16 at 06:49
  • This is as documented https://msdn.microsoft.com/library/cb3sbadh(v=vs.110).aspx *Appends a copy of the specified string followed by the default line terminator to the end of the current StringBuilder object.* – Sir Rufo Oct 18 '16 at 06:59

2 Answers2

1

I see that the string you copy to the clipboard ends with a new line. Of course this new line is pasted and thus your cursor is on the new line.

Somehow you have to get rid of this new line. The method to do this depends on your precise specifications:

If the string is copied to the clipboard, the complete string is copied to the clipboard

If this is your specification, then everyone who pastes your copied string will end with the new line at the end of your string. If the paster is a program that you can't control, you can't do anything about it.

Another specification could be:

If the string is copied to the clipboard, all but a possible terminating new line is copied to the clipboard

This way you'll get what you want, pasters won't see the terminating new line. But be aware that this way the string on the clipboard is not the original string.

Code (of course this can be optimized, just showing small steps)

StringBuilder sbItems = FillStringBuilder(...);
// before copying, remove a possible new line character
// for this we use property System.Environment.NewLine
var stringToCopyToClipboard = sbItems.ToString();
if (stringToCopyToClipboard.EndsWith(Environment.NewLine)
{
    int newLineIndex = stringToCopyToClipboard.LastIndexOf(Environment.NewLine);
    stringToCopyToClipboard = stringToCopyToClipboard.Substring(0, newLineIndex);
}
Clipboard.SetText(stringToCopyToClipboard);
Harald Coppoolse
  • 28,834
  • 7
  • 67
  • 116
0

Just Trim() the string

Returns a new string in which all leading and trailing occurrences of a set of specified characters from the current String object are removed.

Clipboard.SetText(sbItems.ToString().Trim());
mybirthname
  • 17,949
  • 3
  • 31
  • 55