Question

I have a tab control through which the user can right-click within one of several richTextBoxes. The textBoxes use the same contextMenuStrip control, and I need to determine which textBox is the active one within the contextMenuStripCopyPaste_Opening event. I would think that the code to determine this would be tabControl1.SelectedTab.ActiveControl.Name but the ActiveControl property is not available. this.ActiveControl.Name just gives me the name of the tabControl.

How can I determine which textBox is the active control within the tabControl?

Was it helpful?

Solution

You can use the sender paramter to get the ContextMenuStrip then call the ContextMenuStrip.SourceControl property to get the control that opened the context menu.

In this case you can try the following code.

private void contextMenuStrip1_Opening(object sender, CancelEventArgs e)
{
    var ctxStrip = sender as ContextMenuStrip;
    if (ctxStrip == null)
        return;

    var rtb = ctxStrip.SourceControl as RichTextBox;
    if (rtb == null)
        return;
}

This code simply casts the sender object to a ContextMenuStrip if this is null then return. (Although should never be). The next line captures the SourceControl and casts the control to a RichTextBox.

If the source control is not a RichTextBox then the result will be null and we cancel as this shouldn't be null unless you bind the context menu to other controls aswell.

OTHER TIPS

I'm not finding anything that is there by default. I would create a list of the rich text boxes, and then use a LINQ statement as the LINQ Select statement would return only the rich text box that has the focus. Something like this.

List rtbList = new List {RichTextBox1, RichTextBox2, RichTextBox3, RichTextBox4}

var FocusedRTB = rtbList.Select(x => x.Focused == true);

switch (FocusedRTB.Name)

{Execute Code for each RichTextBox }

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top