Tùng Vương
Tùng Vương

Reputation: 15

Detect when user select text in richTextBox

I'm making a form with tabcontrol. When user open a new tab, the program will create new rtb like this:

RichTextBox rtb = new RichTextBox();
TabPage tb = new TabPage();
tb.Text = textBox1.Text;
tabControl.TabPages.Add(tb);
rtb.Parent = tb;
rtb.Dock = DockStyle.Fill;

This is how can I access the richTextBox of current selected tabpage:

RichTextBox rtb = tabControl1.SelectedTab.Controls[0] as RichTextBox;

I'm wondering how can I get the SelectionChanged event of this rtb?

Upvotes: 1

Views: 673

Answers (2)

John Arlen
John Arlen

Reputation: 6689

Ryan's answer is correct. But you can do this with the designer as well.

  • Select your RichTextBox
  • Bring up Properties (F4 is the default)
  • Click the [Events] button (green in image below)
  • Double-click "SelectionChanged" (red in image below)

enter image description here

Upvotes: 0

Ryan Fleming
Ryan Fleming

Reputation: 189

Per Ken-White's comment, you need to attach onto the SelectionChanged event

{
     rtb.SelectionChanged += SelectionChangedEventHandler;
}

void SelectionChangedEventHandler(object sender, EventArgs ev)
{
    RichTextBox rb = sender as RichTextBox;
    Console.WriteLine(rb.SelectedText);
}

Upvotes: 1

Related Questions