如何在用C#/ .NET 2.0编写的Windows应用程序中实现"复制"菜单项?
我想让用户在控件中标记一些文本,然后从应用程序的菜单栏中的"编辑"菜单中选择"复制"菜单项,然后执行粘贴,例如Excel.
让我头脑旋转的是如何首先确定哪个子表单处于活动状态,然后如何找到包含应该复制到剪贴板的标记文本的控件.
请帮忙.
在我和我的一位同事编程的帮助下,我想出了这个,随意重构.
代码放在主窗体中.copyToolStripMenuItem_Click方法处理"编辑"菜单中"复制"菜单项上的"单击"事件.
////// Recursively traverse a tree of controls to find the control that has focus, if any /// /// The control to search, might be a control container ///The control that either has focus or contains the control that has focus private Control FindFocus(Control c) { foreach (Control k in c.Controls) { if (k.Focused) { return k; } else if (k.ContainsFocus) { return FindFocus(k); } } return null; } private void copyToolStripMenuItem_Click(object sender, EventArgs e) { Form f = this.ActiveMdiChild; // Find the control that has focus Control focusedControl = FindFocus(f.ActiveControl); // See if focusedControl is of a type that can select text/data if (focusedControl is TextBox) { TextBox tb = focusedControl as TextBox; Clipboard.SetDataObject(tb.SelectedText); } else if (focusedControl is DataGridView) { DataGridView dgv = focusedControl as DataGridView; Clipboard.SetDataObject(dgv.GetClipboardContent()); } else if (...more?...) { } }