VisualStudio customize paste operation for my component at design-time

66 views Asked by At

I created WinForm component and I want to replace some properties of my component when developer copy and then paste(not when copy but when paste) component from clipboard at design time.

VisualStudio creates new copy of component and assign properties so it became copy of the source component.

I need to replace some properties on paste operation depending on the selected component.

It is very similar to standard Copy/Paste operation with Control component. When designer change Parent of component if developer select other container (like Panel) before Paste Control.

I think that code to perform it should be somewhere in my ComponentDesigner class. I explored ComponentDesigner methods but can't find any methods that controls clipboard operations.

1

There are 1 answers

1
Olivier Jacot-Descombes On

You can override the OnParentChanged method of your component, which is executed when the component is pasted onto the form. Then test the DesignMode property to make sure you are in design mode:

public class MyComponent : Label
{
    protected override void OnParentChanged(EventArgs e)
    {
        if (DesignMode) {
            // Change properties as desired.
            Text = "Design";
        }
        base.OnParentChanged(e);
    }
}

When the component is dropped from the Toolbox, this code is not executed. (I can't explain why, but it happens to be exactly what we need.)


If you derived your component from System.ComponentModel.Component, you can override the property Site; however, this will require some more logic to check whether the component has been pasted.

public override ISite Site
{
    get {
        return base.Site;
    }

    set {
        base.Site = value;
        if (value?.Container is IDesignerHost dh &&
            dh.TransactionDescription == "Paste components") {

            MessageBox.Show("Pasted");
        }
    }
}

But probably the transaction description is localized, because it is the text that you see in the drop-down of the Undo button on the toolbar of Visual Studio after having pasted the component.