How to implement the menu Edit & # 8594; Copy in C # /. Net

How to implement the Copy menu item in a Windows application written in C # /. NET 2.0?

I want the user to be able to mark some text in the control, and then select the "Copy" menu item in the "Edit" menu in the application menu bar, and then do "Paste", for example, in Excel.

What makes my head spin, how to determine which child form is active, and then how to find a control that contains the tagged text that should be copied to the clipboard.

Help me please.

+3
source share
5 answers

- , .

. copyToolStripMenuItem_Click Click "" "".

    /// <summary>
    /// Recursively traverse a tree of controls to find the control that has focus, if any
    /// </summary>
    /// <param name="c">The control to search, might be a control container</param>
    /// <returns>The control that either has focus or contains the control that has focus</returns>
    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?...)
        {
        }
    }
+5

, , Form.ActiveMDIChild, . :

1) Form (, FormFoo), GetCopiedData(), , - :

((FormFoo)this.ActiveMDIChild).GetCopiedData();

, GetCopiedData , , .

2) , -, :

Form f = this.ActiveMDIChild;
if(f is FormGrid)
{
    ((FormGrid)f).GetGridCopiedData();
} else if(f is FormText) {
    ((FormText)f).GetTextCopiedData();
}

.

. GridView, .

+1
0

, DataGridView, , Form TabControl , , DataGridView.

, DataGridView: -

private void dataGridView_CellMouseDown ( , DataGridViewCellMouseEventArgs e)

{

 if (e.Button == MouseButtons.Right)
 {
      dataGridView.Focus();

      dataGridView.CurrentCell = dataGridView[e.ColumnIndex, e.RowIndex];
 }

}

0

, /. , , .

. MDI? , . , . datagridview, . DataGridView.SelectionChanged . - MessageBox.Show("I copied your datas!");.

, , , , .

datagrid, . , , , , .

-1

Source: https://habr.com/ru/post/1696867/


All Articles