Search code examples
c#widthdetect

C# Detect UserControl width


I am using Windows Forms and I want to detect my UserControl Width and change AnchorStyle if Width been reached it limits.

Here is my Code I tried to write.

        if (ucControl.Width > 600)
        {
            ucControl.Anchor = AnchorStyles.None;
            ucControl.Anchor = (AnchorStyles.Bottom | AnchorStyles.Top);
        }
        else
        {
            ucControl.Anchor = (AnchorStyles.Bottom | AnchorStyles.Top | AnchorStyles.Right | AnchorStyles.Left);
        }

For now what it does is when I resize, it is already Top and Bottom Anchor. But I need Top and Bottom only when it reaches 600 and else put anchor in all directions when it is less than 600.


Solution

  • Try the Resize event of your user control:

    public UserControl1()
    {
         InitializeComponent();
         this.Resize += UserControl1_Resize;
    }
    
    private void UserControl1_Resize(object sender, EventArgs e)
    {
        if (this.Width > 600)
            ...
    }