有时,您需要提供一个命令,该命令针对当前活动子窗体中具有焦点的控件进行操作。 例如,假设要将所选文本从子窗体的文本框复制到剪贴板。 你将创建一个过程,该过程使用 Click 标准“编辑”菜单上的“复制”菜单项的事件将所选文本复制到剪贴板。
由于 MDI 应用程序可以有多个相同子窗体的实例,因此过程需要知道应该使用哪个窗体。 若要指定正确的窗体,请使用属性 ActiveMdiChild ,该属性返回具有焦点或最近处于活动状态的子窗体。
在窗体上有多个控件时,还需要指定哪个控件处于活动状态。 与属性 ActiveMdiChild 一样,该 ActiveControl 属性返回焦点位于活动子窗体上的控件。 下面的过程演示了可从子窗体菜单、MDI 窗体上的菜单或工具栏按钮调用的复制过程。
确定活动 MDI 子窗口(将其文本复制到剪贴板)
在一个方法中,将活动子窗体中活动控件的文本复制到剪贴板。
注释
本示例假定有一个 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."); } } }