Sometimes when we are customizing a control, for some reason (for example, to prevent mis-operation at design time), you want to prohibit resizing (Height or Width) of the custom control. It was the simplest way to achieve this:
public class MyButton:System.Windows.Forms.Button
{
... ...
protected override Voidonresize (EventArgs e)
{
This. Height = 23;
This. Width = 75;
}
}
But I am not satisfied with this effect, if you can achieve like a textbox, in the design of the top and bottom edge of the small square is gray, and the left and right edge of the small square is white (indicating that the height cannot be adjusted), then how cool! After some research and to CSDN to help, finally solved this problem, the effect as shown:
Now put the code out, hope to be helpful to everyone.
1. Create a custom control designer class.
<summary>
Custom control designer Classes
</summary>
public class MyButtonDesigner:System.Windows.Forms.Design.ControlDesigner
{
Public Mybuttondesigner ()
{
}
public override Selectionrules Selectionrules
{
Get
{
Adjusting the height of the control is not allowed, as detailed in MSDN.
Selectionrules rules = Selectionrules.visible | selectionrules.moveable |
selectionrules.leftsizeable | selectionrules.rightsizeable;
return rules;
}
}
}
2. Add a property to the custom control class to associate the control class with the designer class defined above.
[Designer (typeof (Mybuttondesigner))]
public class MyButton:System.Windows.Forms.Button
{
... ...
}
After the above treatment, the above effect is achieved. But if you look at it again, you'll find that it works only at design time, and at run time, you can change the height of the control. How can we avoid this problem? Please include the following code in the appropriate location (please refer to MSDN If you have any unclear points).
public class MyButton:System.Windows.Forms.Button
{
... ...
protected override void Setboundscore (int x, int y, int width, intheight,
BoundsSpecified specified)
{
Base. Setboundscore (x, y, width, specified);
}
}
Finally, to remind you: to successfully complete the compilation, you must add a system.design reference, and the file header plus:
Using System.Windows.Forms.Design;
Disable resizing of custom controls