Click here to Skip to main content
15,910,981 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi.
I want to create a richtextbox within "already code", like this:
HTML
#include "stdio.h"
#include "conio.h"
int main()
{
     // position 52 is here
     return 0;
}

I put it in Form_Load.
The size of my RichTextBox is large and allows "multi-line".

I wanna that whenever I type text (in event TextChanged), it will load the keywords to compare (I had done the code in this case, that's ok).

When I press F5 to Start, the "already code" is shown without problem.
But I cannot continue type any text into position 52++. Because only 1 character is accepted.

Here is my code:
C#
// Write code automatically
            this.WritingTextbox.Text = "#include \"stdio.h\""
                                     + Environment.NewLine + "#include \"conio.h\""
                                     + Environment.NewLine + "int main()"
                                     + Environment.NewLine + "{"
                                     + Environment.NewLine + "\t"
                                     + Environment.NewLine + "\treturn 0;"
                                     + Environment.NewLine + "}";

            this.WritingTextbox.Focus();
            this.WritingTextbox.SelectionStart = 52;


When I type: "abc"
The character 'a' is stored at position 53.
The character 'b' and 'c' are stored at position "WritingTextbox.Text.Length".

Can you tell me why and how to fix it?
I wanna the string "abc" is still stored at position "52++".
I'm using C# and RichTextbox.

Many thanks!
Posted
Updated 5-Dec-14 21:30pm
v3
Comments
BillWoodruff 5-Dec-14 12:29pm    
Is this WinForms or WPF or ????

I cannot duplicate the behavior you observe in WinForms, but I tried inserting the Text when a Button was clicked. I suspect you are inserting the Text in some other way, and that way may be impacting behavior.

So: how/when do you insert this text. Also, is WordWrap here 'true or false ?
user8x86 5-Dec-14 12:33pm    
Sorry Mr. BillWoodruff. I'm not clearly.
It's WinForm. And the code will be show when form loading.
BillWoodruff 5-Dec-14 13:23pm    
I can't duplicate this behavior when the code is in the Form Load.

What version of Visual Studio and .NET Framework are you using ?

Here's two things to try to see if you can isolate this problem:

1. define a 'Shown EventHandler for the Form and move the code there and test.

2. put a Button on your Form, move the code to the Button's Click EventHandler and test.
user8x86 6-Dec-14 3:35am    
Thank you. But I wanna put it in event TextChanged. Is there anyway?
BillWoodruff 6-Dec-14 7:31am    
Inserting text into a RichTextBox in the TextChanged Event is not something you want to do: it's going to trigger recursion and stack-overflow.

I'm afraid the unusual behavior you are observing, which, as my answer to you shows, cannot be duplicated in VS 2013/4 using .NET FrameWork 4.5, is the kind of thing that I would have to be at your computer to set break-points and monitor everything your code does to make progress on.

Did you try moving the insert to the 'Shown Event as I suggested ? Or putting a Button on the Form and inserting in its Click EventHandler ? If either one of those methods did not show the same behavior, that would be a clue.

Also, check your shortcuts enabled setting; set it to 'true if its 'false now and see if, by chance, that makes a difference.

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:
C#
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
 
Share this answer
 
v3
Comments
BillWoodruff 5-Dec-14 20:03pm    
+1 Another stunning fantasia mixed with the usual sermonizing.
Sergey Alexandrovich Kryukov 5-Dec-14 20:13pm    
Are you serious? This is working, and the behavior is explained. I performed appropriate testing before publishing the solution.
Please, if you say such things, be so kind to present some evidence for your opinion.
—SA
While my learned colleague, SAK, has given a magnificent peroration on the anatomy of the RichTextBox, citing ancient sources in his own head (fossil remnants of trance-states ?), and wisdom of the ancients that he channels (none of whom ever "looked in the horse's mouth" to actually observe the horse's teeth) ...

This humble flea dares to actually perform an experiment to verify his assumption that the OP has some kind of unusual problem unrelated to the particular way they have inserted Text into a RichTextBox.

Put three RichTextBoxes on a Form, and execute this code in the Form_Load Event, or Form_Shown EventHandler, or anywhere else you please that won't cause a compile error:
C#
private void Form1_Load(object sender, EventArgs e)
{
    this.richTextBox1.Text = "#include \"stdio.h\""
    + Environment.NewLine + "#include \"conio.h\""
    + Environment.NewLine + "int main()"
    + Environment.NewLine + "{"
    + Environment.NewLine + "\t"
    + Environment.NewLine + "\treturn 0;"
    + Environment.NewLine + "}";
    
    this.richTextBox2.Text = "#include \"stdio.h\""
    + "\r" + "#include \"conio.h\""
    + "\r" + "int main()"
    + "\r" + "{"
    + "\r" + "\t"
    + "\r" + "\treturn 0;"
    + "\r" + "}";
    
    this.richTextBox3.Text = "#include \"stdio.h\"\n#include \"conio.h\"\nint main()\n{\n\t\n\treturn 0;\n}";
    
    string t1 = richTextBox1.Text;
    string t2 = richTextBox2.Text;
    string t3 = richTextBox3.Text;
    
    bool sameString = true;
    
    if (t1.Length != t2.Length || t1.Length != t3.Length || t2.Length != t3.Length)
    {
        sameString = false;
    }
    else
    {
    
    for (int i = 0; i < richTextBox1.Text.Length; i++)
    {
        if (t1[i] != t2[i] || t1[i] != t3[i] || t2[i] != t3[i])
        {
            sameString = false;
            break;
        }
    }

    Console.WriteLine("strings are the same: " + sameString.ToString());
}
Observe the result in the 'Output Window, and decide for yourself if there is any difference in these three ways of inserting Text into a RichTextBox.
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 5-Dec-14 20:26pm    
I'm really sorry. It that really you?

You managed to completely ignore the point of the question: this is not about inserting text. OP assigned the text to the control Text. The problem is insertion point; OP focuses and sets the selection start at some position. Please read it again; and ready my solution; and you can test it and look at the related detail. And I never did any assumption on any unusual behavior of RichEdit, just the opposite, this behavior is quite logical.

Please try not to put your own works in one's mouth.

Please, don't consider my voting as a reaction to yours; I never ever do such things. This is only related to your solution. Probably, there is nothing wrong in your code; it simply does not address the OP's problems; neither it addresses possible problems of my answer. Also note that insertion of any combination of "\n", "\r" won't do anything bad. The comparison of the code fragments you suggested won't reveal anything. But this operations will give different length of the text if measured by length of the string added and the length of the Text property.

And also, I would ask you to refrain from generalizations, all those "usual sermonizing", "fossil remnants" and the like. I did not give you any reason to behave like that. This is simply indecent. Sorry.

—SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900