You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

VB.NET Windows Form居中绘制线条问题求助(ClientSize相关)

Windows Form VB.NET 居中绘制线条解决方案

你的代码存在几个核心问题导致无法保持居中:

  • 初始化时计算的ClientSize、centreX、x1等变量不会随窗口大小变化更新,窗口 resize 后坐标还是旧值
  • 使用全局CreateGraphics()而非Paint事件自带的e.Graphics,绘制内容会在窗口重绘时丢失,且资源释放逻辑错误
  • Load和Resize事件里的控件位置计算依赖旧的坐标值,resize后控件位置也会偏移

修复后的完整代码

Dim compteur As Integer = 0

Private Sub Form3_Paint(sender As Object, e As PaintEventArgs) Handles MyBase.Paint
    ' 每次Paint时重新计算最新的窗口中心及相关坐标
    Dim centreX As Integer = Me.ClientSize.Width \ 2
    Dim centreY As Integer = Me.ClientSize.Height \ 2
    Dim x1 As Integer = centreX - 50
    Dim y1 As Integer = centreY - 50
    Dim x2 As Integer = centreX + 50
    Dim y2 As Integer = centreY + 50
    Dim iFormHeight As Integer = Me.ClientSize.Height
    Dim iFormWidth As Integer = Me.ClientSize.Width

    ' 使用Paint事件提供的Graphics对象,无需手动创建和Dispose
    Using pen1 As New Pen(Color.Red)
        e.Graphics.DrawLine(pen1, 0, y1, x1, y1)
        e.Graphics.DrawLine(pen1, x1, 0, x1, y1)
        e.Graphics.DrawLine(pen1, x2, y1, x2, 0)
        e.Graphics.DrawLine(pen1, x2, y1, iFormWidth, y1)
        e.Graphics.DrawLine(pen1, 0, y2, x1, y2)
        e.Graphics.DrawLine(pen1, x1, y2, x1, iFormHeight)
        e.Graphics.DrawLine(pen1, x2, y2, x2, iFormHeight)
        e.Graphics.DrawLine(pen1, x2, y2, iFormWidth, y2)
    End Using ' Using块会自动释放Pen资源
End Sub

Private Sub Form3_Load(sender As Object, e As EventArgs) Handles MyBase.Load, MyBase.Resize
    ' 每次Load/Resize时重新计算坐标,更新控件位置
    Dim centreX As Integer = Me.ClientSize.Width \ 2
    Dim centreY As Integer = Me.ClientSize.Height \ 2
    Dim x1 As Integer = centreX - 50
    Dim y1 As Integer = centreY - 50
    Dim x2 As Integer = centreX + 50
    Dim y2 As Integer = centreY + 50

    hautgauche.Location = New Point(x1 - basdroit.Width, y1 - basdroit.Height)
    basdroit.Location = New Point(x2, y2)
    hautdroit.Location = New Point(x2, y1 - basdroit.Width)
    basgauche.Location = New Point(x1 - basdroit.Height, y2)
    Timer1.Start()
End Sub

关键修改说明

  • 把所有依赖窗口大小的坐标计算移到Paint和Resize事件内部,每次触发事件时都用最新的ClientSize值,确保窗口大小变化后坐标自动更新
  • 不再使用全局CreateGraphics(),改用Paint事件参数里的e.Graphics,这是WinForm绘制的标准方式,能保证重绘时内容不丢失
  • 使用Using块管理Pen对象,自动释放资源,避免手动Dispose导致的错误
  • Resize事件里重新计算控件位置,确保窗口大小变化后控件也保持对应居中位置

内容的提问来源于stack exchange,提问作者Moâtaz Belkouadssi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 07:05:19