如何:确定活动的 MDI 子窗体

有时,你可能希望提供一个对控件进行操作的命令,该控件的焦点是当前活动的子窗体。 例如,假设你想要将子窗体文本框中的选定文本复制到剪贴板。 你将创建一个过程,使用标准“编辑”菜单上“复制”菜单项的 Click 事件将所选文本复制到剪贴板。

由于 MDI 应用程序可以具有同一子窗体的多个实例,因此该过程需要了解要使用哪个窗体。 若要指定正确的窗体,请使用 ActiveMdiChild 属性,该属性返回具有焦点或最近处于活动状态的子窗体。

在窗体上有多个控件时,还需指定哪个控件处于活动状态。 与 ActiveMdiChild 属性一样,ActiveControl 属性返回焦点位于活动子窗体上的控件。 下面的过程演示了可从子窗体菜单、MDI 窗体上的菜单或工具栏按钮调用的复制过程。

确定(要将其文本复制到剪贴板的)活动的 MDI 子窗体

  1. 在该方法中,将活动子窗体的活动控件的文本复制到剪贴板。

    注意

    此示例假定有一个 MDI 父窗体 (Form1),它具有一个或多个包含 RichTextBox 控件的 MDI 子窗口。 有关详细信息,请参阅创建 MDI 父窗体

    Public Sub mniCopy_Click(ByVal sender As Object, _  
       ByVal e As System.EventArgs) Handles mniCopy.Click  
    
       ' Determine the active child form.  
       Dim activeChild As Form = Me.ActiveMDIChild  
    
       ' If there is an active child form, find the active control, which  
       ' in this example should be a RichTextBox.  
       If (Not activeChild Is Nothing) Then  
          Dim theBox As RichTextBox = _  
            TryCast(activeChild.ActiveControl, RichTextBox)  
    
          If (Not theBox Is Nothing) Then  
             'Put selected text on Clipboard.  
             Clipboard.SetDataObject(theBox.SelectedText)  
          Else  
             MessageBox.Show("You need to select a RichTextBox.")  
          End If  
       End If  
    End Sub  
    
    protected void mniCopy_Click (object sender, System.EventArgs e)  
    {  
       // Determine the active child form.  
       Form activeChild = this.ActiveMdiChild;  
    
       // If there is an active child form, find the active control, which  
       // in this example should be a RichTextBox.  
       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("You need to select a RichTextBox.");  
          }  
       }  
    }  
    

另请参阅