<p>How do I implement a Copy menu item in a Windows application written in C#/.NET 2.0?</p>

<p>I want to let the user to mark some text in a control and then select the Copy menu item from an Edit menu in the menubar of the application and then do a Paste in for example Excel. </p>

<p>What makes my head spin is how to first determine which child form is active and then how to find the control that contains the marked text that should be copied to the clipboard. </p>

<p>Help, please.</p>

[{'answer_id': 62833, 'author': 'GEOCHET', 'author_id': 5640, 'author_profile': 'https://Stackoverflow.com/users/5640', 'pm_score': -1, 'selected': False, 'text': '<p>It seems to me that you might be better off breaking this into smaller tasks/questions.\nYou have a few issues you are stuck on from the way it sounds.</p>\n\n<p>You have multiple \'child\' windows open. Is this an MDI application?\nWhen an action is performed on one of those child windows, it should fire an event in that window\'s event handlers. That is your first thing to set up. If this is a datagridview I would suggest a simple test to start. Try trapping the <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.selectionchanged.aspx" rel="nofollow noreferrer">DataGridView.SelectionChanged</a> event. Just throw in something like <code>MessageBox.Show("I copied your datas!");</code> for now.</p>\n\n<p>This should get you started where you will at least understand how this event will be raised to you.</p>\n\n<p>From here, we will need to know a little more about your datagrid, and the rows and child controls in those rows. Then we can likely create events in the render events that will be raised at the appropriate times, with the appropriate scope.</p>\n'}, {'answer_id': 62907, 'author': 'Drejc', 'author_id': 6482, 'author_profile': 'https://Stackoverflow.com/users/6482', 'pm_score': 0, 'selected': False, 'text': '<p>Why not extending the control, so the control itself provides the data which should be copied into the clipboard.</p>\n\n<p>Take a look at <a href="http://msdn.microsoft.com/en-us/library/system.windows.input.applicationcommands.aspx" rel="nofollow noreferrer">ApplicationCommands</a> documentation.</p>\n'}, {'answer_id': 63004, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 1, 'selected': False, 'text': "<p>To determine which window is open, you can query the Form.ActiveMDIChild property to get a reference to the currently active window.  From there, you can do one of two things:</p>\n\n<p>1) If you create your own custom Form class (FormFoo for example) that has a new public member function GetCopiedData(), then inherit all of your application's child forms from that class, you can just do something like this:</p>\n\n<pre><code>((FormFoo)this.ActiveMDIChild).GetCopiedData();\n</code></pre>\n\n<p>Assuming the GetCopiedData function will have the form-specific implementation to detect what text should be copied to the clipboard.</p>\n\n<p>or</p>\n\n<p>2) You can use inheritance to detect the type of form that is active, and then do something to get the copied data depending on the type of form:</p>\n\n<pre><code>Form f = this.ActiveMDIChild;\nif(f is FormGrid)\n{\n    ((FormGrid)f).GetGridCopiedData();\n} else if(f is FormText) {\n    ((FormText)f).GetTextCopiedData();\n}\n</code></pre>\n\n<p>etc.</p>\n\n<p>That should get you started with finding the active window and how to implement a copy function.  If you need more help copying out of a GridView, it may be best to post another question.</p>\n"}, {'answer_id': 63470, 'author': 'Petteri', 'author_id': 7174, 'author_profile': 'https://Stackoverflow.com/users/7174', 'pm_score': 4, 'selected': True, 'text': '<p>With the aid of some heavy pair programming a colleague of mine and I came up with this, feel free to refactor.</p>\n\n<p>The code is placed in the main form. The copyToolStripMenuItem_Click method handles the Click event on the Copy menu item in the Edit menu.</p>\n\n<pre><code>    /// &lt;summary&gt;\n    /// Recursively traverse a tree of controls to find the control that has focus, if any\n    /// &lt;/summary&gt;\n    /// &lt;param name="c"&gt;The control to search, might be a control container&lt;/param&gt;\n    /// &lt;returns&gt;The control that either has focus or contains the control that has focus&lt;/returns&gt;\n    private Control FindFocus(Control c) \n    {\n        foreach (Control k in c.Controls)\n        {\n            if (k.Focused)\n            {\n                return k;\n            }\n            else if (k.ContainsFocus)\n            {\n                return FindFocus(k);\n            }\n        }\n\n        return null;\n    }\n\n    private void copyToolStripMenuItem_Click(object sender, EventArgs e)\n    {\n        Form f = this.ActiveMdiChild;\n\n        // Find the control that has focus\n        Control focusedControl = FindFocus(f.ActiveControl);\n\n        // See if focusedControl is of a type that can select text/data\n        if (focusedControl is TextBox)\n        {\n            TextBox tb = focusedControl as TextBox;\n            Clipboard.SetDataObject(tb.SelectedText);\n        }\n        else if (focusedControl is DataGridView)\n        {\n            DataGridView dgv = focusedControl  as DataGridView;\n            Clipboard.SetDataObject(dgv.GetClipboardContent());\n        }\n        else if (...more?...)\n        {\n        }\n    }\n</code></pre>\n'}, {'answer_id': 1207426, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': "<p>If the form is tabbed and the target control is a DataGridView, it's sometimes possible for the Form's TabControl to be returned as the active control, using the above method, when the DataGridView is right clicked upon.</p>\n\n<p>I got around this by implementing the following handler for my DataGridView:-</p>\n\n<p>private void dataGridView_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)</p>\n\n<p>{</p>\n\n<pre><code> if (e.Button == MouseButtons.Right)\n {\n      dataGridView.Focus();\n\n      dataGridView.CurrentCell = dataGridView[e.ColumnIndex, e.RowIndex];\n }\n</code></pre>\n\n<p>}</p>\n"}]
['https://Stackoverflow.com/questions/62776', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7174/']