当前位置:  开发笔记 > 编程语言 > 正文

如何在c#/ .net中实现编辑 - >复制菜单

如何解决《如何在c#/.net中实现编辑->复制菜单》经验,为你挑选了1个好方法。

如何在用C#/ .NET 2.0编写的Windows应用程序中实现"复制"菜单项?

我想让用户在控件中标记一些文本,然后从应用程序的菜单栏中的"编辑"菜单中选择"复制"菜单项,然后执行粘贴,例如Excel.

让我头脑旋转的是如何首先确定哪个子表单处于活动状态,然后如何找到包含应该复制到剪贴板的标记文本的控件.

请帮忙.



1> Petteri..:

在我和我的一位同事编程的帮助下,我想出了这个,随意重构.

代码放在主窗体中.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?...)
        {
        }
    }

推荐阅读
Gbom2402851125
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有