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

如何在PictureBox上实现鼠标绘制矩形?附Form绘制示例代码

在PictureBox上实现鼠标绘制矩形的方法

嗨,我来帮你把这个绘制矩形的功能迁移到PictureBox上~其实核心逻辑和你在Form上写的差不多,只需要做几个关键的小调整就行,我给你拆解清楚:

关键改动点

  • 把所有鼠标事件的处理对象从Form换成你的PictureBox控件,比如把Form1_MouseDown改成PictureBox1_MouseDown,同时事件的Handles要指向PictureBox1.MouseDown(注意替换成你实际的PictureBox控件名)
  • 绘制可逆虚线框时,要使用PictureBox的坐标转换方法PictureBox1.RectangleToScreen,而不是Form的Me.RectangleToScreen,因为现在的矩形坐标是相对于PictureBox的
  • 最终绘制实线矩形时,要获取PictureBox的Graphics对象,也就是用PictureBox1.CreateGraphics(),而不是Form的Me.CreateGraphics()

修改后的完整代码

Public Class Form1
    Dim SelectRect As Rectangle = New Rectangle()
    Dim ps As Point = New Point()
    Dim pe As Point = New Point()

    ' 捕获PictureBox上的首次点击,记录矩形起始点
    Private Sub PictureBox1_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles PictureBox1.MouseDown
        SelectRect.Width = 0
        SelectRect.Height = 0
        SelectRect.X = e.X
        SelectRect.Y = e.Y
        ps.X = e.X
        ps.Y = e.Y
        pe = ps
    End Sub

    ' 在PictureBox上拖动鼠标时更新矩形范围,绘制可逆虚线框
    Private Sub PictureBox1_MouseMove(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles PictureBox1.MouseMove
        If (e.Button = MouseButtons.Left) Then
            ControlPaint.DrawReversibleFrame(PictureBox1.RectangleToScreen(SelectRect), Color.Black, FrameStyle.Dashed)
            SelectRect.Width = e.X - SelectRect.X
            SelectRect.Height = e.Y - SelectRect.Y
            ControlPaint.DrawReversibleFrame(PictureBox1.RectangleToScreen(SelectRect), Color.Black, FrameStyle.Dashed)
        End If
    End Sub

    ' 松开鼠标后,在PictureBox上绘制最终的蓝色实线矩形
    Private Sub PictureBox1_MouseUp(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles PictureBox1.MouseUp
        Dim g As Graphics = PictureBox1.CreateGraphics()
        Dim p As Pen = New Pen(Color.Blue, 2)
        ControlPaint.DrawReversibleFrame(PictureBox1.RectangleToScreen(SelectRect), Color.Black, FrameStyle.Dashed)
        g.DrawRectangle(p, SelectRect)
        g.Dispose()
        p.Dispose() ' 别忘了释放Pen资源,避免内存泄漏
    End Sub
End Class

额外小提示

我还加了一行p.Dispose()来释放Pen的资源,这样能避免潜在的内存泄漏问题,算是个小优化~

内容的提问来源于stack exchange,提问作者arc95

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 04:37:11