C# 获取winform标题栏的高度
时间: 2024-12-10 22:52:38 浏览: 49
在Windows Forms应用程序中,获取窗体标题栏的高度可以通过以下步骤实现:
1. 首先,你需要一个Form对象,这通常是全局存在的,例如你可以在Form1的构造函数中初始化。
```csharp
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
// 获取标题栏高度
TitleBarHeight = GetTitleBarHeight();
}
private int GetTitleBarHeight()
{
// 标题栏高度一般在非最大化状态下测量,因为最大化时其高度可能会有变化
var screenPoint = this.PointToScreen(new Point(0, 0));
var formSize = this.Size;
var windowFrame = new Rectangle(screenPoint.X, screenPoint.Y, formSize.Width, formSize.Height);
// 获取窗口边框信息
using (var hDC = GetWindowDC(this.Handle))
using (var hMemDC = CreateCompatibleDC(hDC))
using (var brush = new SolidBrush(GetSysColor(COLOR_BTNFACE)))
using (var pen = new Pen(brush.Color))
{
SelectObject(hMemDC, CreateCompatibleBitmap(hDC, this.ClientSize.Width, this.ClientSize.Height));
// 绘制窗口边框
DrawEdge(hMemDC, windowFrame, EDGE_RAISED, EdgeStyle.All);
// 获取边框宽度
int borderWidth = (int)(pen.GetWidth(hDC) * 72 / Application.DpiX); // 转换为像素值
// 减去边框宽度得到标题栏高度
return this.Height - borderWidth;
}
}
}
```
上述代码计算了标题栏高度,它等于窗体的高度减去窗口边框的宽度。
阅读全文
相关推荐


















