Is this correct code to setup a dynamic Edit → Copy mnuStripItem?
This code is used to copy any highlighted by the user and it does output properly.
private void copyToolStripMenuItem_Click(object sender, EventArgs e)
{
Form f = Form.ActiveForm;
// Find the control that has focus
Control focusedControl = 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?...)
//{
//}
}
It is absolutely correct, but normally when I have to deal with a lot of check statements, I prefer to use a switch statement. It is easier to read and i think it will also be more performing in this case (no need to use “is” and “as” statements):