I have custom control inherited from UserControl. I need to ensure that it is squared. So, I need smth like that:
int side = Math.Max(this.Width, this.Height);
this.Size = new Size(side, side);
But where should I implement this logic? I cannot do it in OnResize because it causes recursive calls and crashes Visual Studio in design mode, or app in runtime.
To keep a squared aspect, I suggest to override OnLayout
instead of OnResize
, the latter can be called more than once when the UserControl is resized in the Form designer or at run-time.
OnLayout
is called multiple times when the UC is first created (it has to, the size is set multiple time in the initialization).
You also need to check whether the UserControl's Size is scaled down or up:
Math.Max(Width, Height)
Math.Min(Width, Height)
You have perform this check otherwise, when - for example - the US is scaled up, you won't be able to resize it to a value that is lower that Max(Width)
or Max(Height)
(ie, when scaled up, it won't ever scale down).
public partial class MyUserControl : UserControl
{
int m_Squared = 0;
public MyUserControl()
{
InitializeComponent();
// Test with and without setting these
this.MaximumSize = new Size(100, 100);
this.MinimumSize = new Size(300, 300);
}
protected override void OnLayout(LayoutEventArgs e)
{
base.OnLayout(e);
m_Squared = (this.Width > m_Squared || this.Height > m_Squared)
? Math.Max(this.Width, this.Height)
: Math.Min(this.Width, this.Height);
this.Bounds = new Rectangle(this.Location, new Size(m_Squared, m_Squared));
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.