简体   繁体   English

在Windows窗体C#中复制粘贴控件

[英]Copy paste control in windows forms C#

I am trying to copy paste a control instance using the clipboard. 我正在尝试使用剪贴板复制粘贴控件实例。 I am able to copy the control but unable to get back the copied object. 我能够复制控件但无法取回复制的对象。

Sample code below. 示例代码如下。

    [Serializable]
public class myControl
{
    private Control _copiedControl;
    public myControl(Control ctrl)
    {
        _copiedControl = ctrl;
    }

    public Control CopiedControl
    { 
        get 
        {
            return _copiedControl;
        }
        set 
        {
            _copiedControl = value;                
        }
    }
}

private void btnCopy_Click(object sender,EventArgs e)
{
    Clipboard.SetData("myControl", new myControl((Control)myButton));
}          

private void btnPaste_Click(object sender, EventArgs e)
{
    if(Clipboard.ContainsData("myControl"))
    {
                // Condition is satisfied here.. 

        myControl obj = Clipboard.GetData("myControl") as myControl;
                    // obj is null and control is lost..
        if(obj != null)
        {
            myPanel.Controls.Add(obj.CopiedControl);
        }
    }
}

I am unable to get the copied control using the GetData() method. 我无法使用GetData()方法获取复制的控件。 I am not sure what is wrong can anyone guide me? 我不确定有什么不对的人可以指导我吗?

You marked your "myControl" serializable but it is not in fact serializable, the Control class does not support binary serialization. 您将“myControl”标记为可序列化但实际上不可序列化,Control类不支持二进制序列化。 Way too much trouble with the runtime state for the window associated with the control, starting with the fact that a window can only ever have a single parent. 对于与控件关联的窗口的运行时状态来说太麻烦了,首先是窗口只能有一个父窗口。 Sadly the Clipboard.SetData() method does not complain about that. 可悲的是,Clipboard.SetData()方法并没有抱怨。

There's a pretty simple workaround for it, the clipboard can only contain a single item and copying between processes is never going to work. 有一个非常简单的解决方法,剪贴板只能包含一个项目,并且进程之间的复制永远不会起作用。 So you might as well fake it and keep your own reference to the control. 所以你不妨假装它并保持自己对控件的引用。 Something like this: 像这样的东西:

    private Control clipBoardRef;

    private void btnCopy_Click(object sender, EventArgs e) {
        clipBoardRef = myButton1;
        Clipboard.SetData("myControl", "it doesn't matter");
    }

    private void btnPaste_Click(object sender, EventArgs e) {
        if (Clipboard.ContainsData("myControl")) {
            Control ctl = clipBoardRef;
            // etc...
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM