C# 如何获取 Winforms Form 标题栏高度的大小?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2022660/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get the size of a Winforms Form titlebar height?
提问by Joan Venge
So if it's toolwindow or a minimizable form, I want to be able to get its height programmatically.
因此,如果它是工具窗口或可最小化的窗体,我希望能够以编程方式获取其高度。
Is this possible? If so how?
这可能吗?如果是这样怎么办?
采纳答案by Ash
You can determine titlebar height for both tool-windows and normal forms by using:
您可以使用以下方法确定工具窗口和普通窗体的标题栏高度:
Rectangle screenRectangle = this.RectangleToScreen(this.ClientRectangle);
int titleHeight = screenRectangle.Top - this.Top;
Where 'this' is your form.
其中“this”是您的表格。
ClientRectangle returns the bounds of the client area of your form. RectangleToScreen converts this to screen coordinates which is the same coordinate system as the Form screen location.
ClientRectangle 返回表单客户区的边界。RectangleToScreen 将此转换为屏幕坐标,该坐标系与 Form 屏幕位置的坐标系相同。
回答by LRaiz
There is an additional wrinkle in case your form is a view in an MDI application. In that case RectangleToScreen(this.ClientRectangle) returns coordinates relative not to Form itself (as one might expect) but with respect to MainForm which hosts MDIClient control hosting the Form.
如果您的表单是 MDI 应用程序中的视图,则还有一个问题。在这种情况下, RectangleToScreen(this.ClientRectangle) 返回的坐标不是相对于 Form 本身(正如人们所期望的),而是相对于承载 MDIClient 控件的 MainForm。
You may to account for that by
你可以通过
Point pnt = new Point(0, 0);
Point corner = this.PointToScreen(pnt); // upper left in MainFrame coordinates
Point origin = this.Parent.PointToScreen(pnt); // MDIClient upperleft in MainFrame coordinates
int titleBarHeight = corner.Y - origin.Y - this.Location.Y;
回答by S. Norman
This will get you the TitleBarsize:
这将为您提供 TitleBarsize:
form.ClientRectangle.Height - form.Height;
回答by amalgamate
To fix S. Norman's answer that simply has his minuend and subtrahend switched, the following is the simplest answer:
要修复 S. Norman 的答案,只需将他的被减数和被减数切换,以下是最简单的答案:
int HeightOfTheTitleBar_ofThis = this.Height - this.ClientRectangle.Height;
int HeightOfTheTitleBar_ofThis = this.Height - this.ClientRectangle.Height;
BTW, the standard hard coded title bar is 25dpi which is the minimum height and can be changed to a maximum of 50dpi.
顺便说一句,标准的硬编码标题栏是 25dpi,这是最小高度,可以更改为最大 50dpi。
OK OK,... yes, it is technically incorrect As stated by Cody Grey but it works and should get the same answer as the accepted answer. No need to create a rectangle.
好的好的,...是的,它在技术上是不正确的,正如科迪·格雷所说,但它有效,应该得到与接受的答案相同的答案。无需创建矩形。