Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make UserControl locked to certain height?

A user is not allowed to resize a TextBox control vertically. The height of a TextBox is locked to the ideal height that a textbox should be.

What's more, Visual Studio doesn't even provide you vertical drag handles:

enter image description here

How do i provide the same mechanism on my UserControl?

like image 328
Ian Boyd Avatar asked Oct 28 '25 06:10

Ian Boyd


1 Answers

I will elaborate on Hans' comment. You can associate specialized code (called a Designer) with a UserControl so that when it is placed on a form in Visual Studio, the user is limited in how they can configure your control.

  1. Add a reference to System.Design in your project.

  2. Use the following sample code:

    [Designer(typeof(FixedHeightUserControlDesigner))]
    public partial class FixedHeightUserControl : UserControl
    {
        private const int FIXED_HEIGHT = 25;
    
        protected override void OnSizeChanged(EventArgs e)
        {
            if (this.Size.Height != FIXED_HEIGHT)
                this.Size = new Size(this.Size.Width, FIXED_HEIGHT);
    
            base.OnSizeChanged(e);
        }
    
        public FixedHeightUserControl()
        {
            InitializeComponent();
    
            this.Height = FIXED_HEIGHT;
        }
    }
    
    public class FixedHeightUserControlDesigner : ParentControlDesigner
    {
        private static string[] _propsToRemove = new string[] { "Height", "Size" };
    
        public override SelectionRules SelectionRules
        {
            get { return SelectionRules.LeftSizeable | SelectionRules.RightSizeable | SelectionRules.Moveable; }
        }
    
        protected override void PreFilterProperties(System.Collections.IDictionary properties)
        {
            base.PreFilterProperties(properties);
            foreach (string p in _propsToRemove)
                if (properties.Contains(p))
                    properties.Remove(p);
        }
    }
    
like image 152
Kevin McCormick Avatar answered Oct 31 '25 08:10

Kevin McCormick



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!