Please see my comment to the question. I have done it for your; all code if fully runnable and works correctly, from the first attempt:
using System;
using System.Windows.Forms;
class MyForm : Form {
internal MyForm() {
RichTextBox tb = new RichTextBox();
string myText = string.Format("some{0}program{0}code(0) {{}}", "\n");
tb.Text = myText;
tb.Dock = DockStyle.Fill;
tb.Parent = this;
Shown += (sender, eventArgs) => {
tb.Focus();
tb.SelectionStart = myText.Length - 1;
};
}
}
static class Program {
[STAThread]
static void Main() {
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MyForm());
}
}
Your main mistake was using
Environment.NewLine
. It's amazing: most people use it and advise to use it, but it's wrong. Rich text is actually the multiplatform format, and it has its universal new line indicator the same for all the platforms ("Environments"), and this is only one character, not two as on Windows ("\r\n").
Actually, it's not even important what character to add in this call; experiments show that either "\n" or "\r" works. This is typical for many UI APIs where it is fixed. The problem is just the estimate of the position where you put insertion point. It should take into account that new like is only one character, not two. Yes, this is a delicate problem… :-)
And of course you idea to hard code your 52 is wrong, as well as the idea to use string concatenation. String is immutable, so repeated concatenation is bad (do I even need to explain why), but, more importantly, your code is not maintainable.
One more important detail: why did I put focusing and the change in cursor position in the event handler of the
Shown
event? You see, in this very case, it would work if you move it into the construction code, without the event handling. But in general case it would be too early. In particular, focusing of something which is not yet shown is impossible.
[EDIT]
Also, please look at my code sample to get a good idea how to ask question, how to provide 100% of code. This code is the complete code file, and this is the only one file in the whole application. I got rid of the code generated by the designer, everything, which helped me to create the whole application in this short sample.
If you try to isolate your problem by writing such a small separate application, chances are, you will see the problem more clearly, so you could solve it by yourself. If not, such code is good for posting in your CodeProject question.
—SA