简体   繁体   中英

C# Cursor/ Caret Not display when Append text in Richtextbox

I am new to Programming, i am making C# Windows Form Application were, on selecting Tree node, it append the text in Richtextbox:

Qs1: For me Caret is not displayed after selecting the tree Node. Qs2: Make display like editor, where if word start with // ( Comment) should be in green color.

Thanks

 if (treeView1.SelectedNode.Name == "Node1")
        {  
          this.richTextBox1.SelectedText += "  my text for Node1" + Environment.NewLine
          richTextBox1.Focus();
        }
        else if (treeView1.SelectedNode.Name == "Node2")
        {
         this.richTextBox1.SelectedText += "  my text for Node2" + Environment.NewLine
          richTextBox1.Focus();
        }

You're asking two questions related to RichTextBox . The preferred form on StackOverflow is one question per question . You'll probably get more responses with more focused questions.

That being said:

  1. According to the documentation for the Select method:

    The text box must have focus in order for the caret to be moved.

    So you need to do that first.

    In addition, as a general rule, you should never modify the pre-existing Text or SelectedText with += because this will clear away any and all RTF formatting on that text. Instead, to insert text, you should set the selection to the desired location, with length zero, and insert there. Thus:

     public static void FocusAndAppendToSelectedText(this RichTextBox richTextBox, string text) { Action append = () => { richTextBox.Focus(); var start = richTextBox.SelectionStart; var length = richTextBox.SelectionLength; var insertAt = start + length; richTextBox.Select(insertAt, 0); richTextBox.SelectedText = text; }; if (richTextBox.InvokeRequired) richTextBox.BeginInvoke(append); else append(); } 

    Also, you should use \\n rather than Environment.Newline because the latter will get simplified into the former anyway.

  2. A question like "[How to] Make display like editor, where if word start with // ( Comment) should be in green color" is very general. Try to break it down into discrete issues and ask questions for those you can't figure out yourself. To get you started, see this question here: highlight the '#' until line end in richtextbox . However, you may want to set the SelectionBackColor not the SelectionColor , depending on your precise UI requirements.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM