Search code examples
winformsunicoderichtextboxhighlighting

Highlight Part of TextBox Text in .Net Windows Form


Requirement

I am using Vistual Studio 2005. I need Textbox which

  • Should support Japanese language. User should be able to paste Japanese text in textbox.
  • Text in textbox should always be Bold.
  • Text after 100 characters should be highlighted in Yellow color when user is typing.
  • Textbox should not allow any other formatted text.

Solution I tried

  1. Normal Textbox with FontStyle set to Bold.
    Issue : I can paste Japanese text and text always remains BOLD. Only issue is textbox does not support highlighting of text as user types.

  2. RichTextBox : Highlight text in TextChanged eventhandler.

    handler = new System.EventHandler(richTextBox1_TextChanged);
    
    private void richTextBox1_TextChanged(object sender, EventArgs e)
    {
        this.richTextBox1.TextChanged -= this.handler;
        int index = richTextBox1.SelectionStart;
    
        richTextBox1.Select(0, richTextBox1.Text.Length);
        richTextBox1.SelectionBackColor = Color.White;
        richTextBox1.SelectionLength = 0;
    
        if (richTextBox1.Text.Length > 100)
        {
            richTextBox1.Select(100, richTextBox1.Text.Length);
            richTextBox1.SelectionBackColor = Color.Yellow;
            richTextBox1.SelectionLength = 0;
        }
    
        richTextBox1.SelectionStart = index;
        this.richTextBox1.TextChanged += this.handler;
    }
    

    Highthing works fine. But there are following issues.

    • When I copy paste Japanese text into richtextbox, it is shown as Squre boxes. But if I assign same japanese text programmatically, it is displayed correctly. Even in normal textbox the pasted text is shown correctly. So not sure what is the problem with richtextbox.

    • I could not disable formatting of richtextbox. e.g. If I copy some html text with hyperlinks and paste in richtextbox, I see the hyperlinks. And my requriment says NO formatting except BOLD is allowed.

I want to acheive this functionality using windows form controls. Third party control would be my last option.

Can someone help?

Thanks in Advance!

~Sambha


Solution

  • I got one solution, but not sure if this is the efficient way of doing it and if it will cause some other issues.

    Solution : Create subclass from RichTextBox and ovverride KeyDown event. Check if Ctrol+V or Shift+Inst key was pressed, call paste method using DataFormats.UnicodeText.

    class MyRichTextBox : RichTextBox
    {
    
    protected override void OnKeyDown(KeyEventArgs e)
    {
        switch (e.KeyData)
        {
            case (Keys.Shift | Keys.Insert): 
            case (Keys.Control | Keys.V):
    
                this.Paste(DataFormats.GetFormat(DataFormats.UnicodeText));
                e.SuppressKeyPress = true;
    
                return;
        }
    
        base.OnKeyDown(e);
    }
    
    }