471,350 Members | 1,723 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 471,350 software developers and data experts.

RichTextBox behaving weirdly

I want to colour certain characters as they are typed in a RichTextBox. I
started with this simple event handler.

private void rtb_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar >= ' ')
{
this.SelectedText = e.KeyChar.ToString();
this.SelectionColor = Color.Blue;

e.Handled = true;
}
}

Why does this code not colour the first character typed into the box? It
works for subsequent characters.

Eq.
Jun 27 '08 #1
1 916
Hmm, okay, it seems that setting SelectedText changes the selection. Here's
what I used in the end.

if (e.KeyChar >= ' ')
{
this.SelectedText = e.KeyChar.ToString();

this.SelectionStart--;
this.SelectionLength++;
this.SelectionColor = GetColourForChar(e.KeyChar);

this.SelectionStart++;
this.DeselectAll();

e.Handled = true;
}

Eq.
Jun 27 '08 #2

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

reply views Thread by nouno | last post: by
3 posts views Thread by kangoo | last post: by
12 posts views Thread by M O J O | last post: by
9 posts views Thread by James Wong | last post: by
3 posts views Thread by michael sorens | last post: by

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.