简体   繁体   中英

C# - Determine the focused RichTextBox in a Split Container of the Active MDI Child

I have a Form (Form2) that contains a Split Container, the RichTextBox is on the Left Panel and the WebBroswer is on the Right Panel.

I am showing the Form as a child of a MDIParent Form 1. What I wanted to do is copy the selected text of the active MDI Child. However due to the RichTextBox being inside a Split Container, I cannot target the RichTextBox and it returns nothing.

Form activeChild = this.ActiveMdiChild;  

if (activeChild != null)  
{    
    try  
    {  
        RichTextBox theBox = (RichTextBox)activeChild.ActiveControl;  
        if (theBox != null)  
        {  
            // Put the selected text on the Clipboard.  
            Clipboard.SetDataObject(theBox.SelectedText);      
        }
    }  
    catch  
    {  
        MessageBox.Show("Unable to Copy to Clipboard");  
    } 
}  

The result is, the Message Box shows so that means I wasn't able to target the RTB properly. How can I get the current active RTB?

Since the ActiveControl being returned from the child form is the SplitContainer control, then we will need to go one level deeper and get the ActiveControl from that container in order to finally get the RichTextBox control. Note that we have to check for the object types and null along the way, in case a different control may be selected.

Here's one way to get the rich text box text (or an empty string if it's not selected):

var childSplitContainer = this.ActiveMdiChild?.ActiveControl is SplitContainer
    ? (SplitContainer)activeChildForm.ActiveControl
    : null;

var splitContainerRTB = childSplitContainer?.ActiveControl is RichTextBox
    ? (RichTextBox)childSplitContainer.ActiveControl
    : null;

Clipboard.SetDataObject(splitContainerRTB?.Text ?? string.Empty);

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