Form height problem when FormBorderStyle is NONE

旧城冷巷雨未停 提交于 2021-02-07 08:23:13

问题


I have a borderless form (FormBorderStyle = None) with the height of 23 pixels (set in the designer)

When .NET draws my form at runtime - it draws it 38 pixels high (it adds the height of a title-bar for some reason).

MessageBox.Show(this.Height.ToString()); //this shows 38!! why?

To work it around I have to set "Height = 23;" in the Form_Load event.

private void MyForm_Load(object sender, EventArgs e)
{
    this.Height = 23; //workaround. wtf??
}

You can try this yourself in Visual Studio 2010 (Winforms App, target Framework - 2.0).

Wtf?


回答1:


Yeah, it is a bug, of sorts. Note how in the designer you set the size of the form with the Width and Height properties. Those properties include the size of the borders and the title bar. That's a problem however, your form may run on a machine where the user has increased, say, the title bar font size. That then would reduce the size of the window's client area. Or in other words, the form's ClientSize property would change on that machine. Leaving less room for the controls and messing up the design of your form pretty badly.

There's code inside the Form class that runs after the Handle is created, right before the Load event runs. It recalculates the Size of the form, using the same ClientSize you had on your machine. Now everything is good, the Height of the form won't match the one you set in the designer but the form otherwise looks the same and the layout of the controls is identical.

That same code also ensures that the window doesn't get too small. And that's where it falls over, it doesn't pay enough attention to the FormBorderStyle property. Clipping the height to the title bar size plus the client area height, as you found out. It also prevents the form getting too narrow, trying to make sure that the icon and min/max/close buttons are always visible. Even if you don't have any.

The workaround is to change the ClientSize after this code runs, the OnLoad override or Load event handler is the right place for that. Beware that if you hard-code the form size like this then you should also set the AutoScaleMode property to None. Make sure that this doesn't cause trouble on a machine that has a different DPI setting.



来源:https://stackoverflow.com/questions/4163655/form-height-problem-when-formborderstyle-is-none

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!