0

这是设置动态Edit→的正确代码Copy mnuStripItem吗?

此代码用于复制用户突出显示的任何内容,并且可以正确输出。

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?...)
        //{
        //}

    }
4

1 回答 1

0

这是绝对正确的,但通常当我必须处理大量的检查语句时,我更喜欢使用 switch 语句。它更容易阅读,我认为在这种情况下它也会表现得更好(不需要使用“is”和“as”语句):

Control focusedControl = f.ActiveControl;

switch (focusedControl.GetType())
{
    case typeof(TextBox):
        TextBox tb = (TextBox)focusedControl;
        Clipboard.SetDataObject(tb.SelectedText);
        break;

    // ...

    default:
        break;
}
于 2013-01-20T00:36:01.827 回答