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

VB.NET中如何设置正确屏幕坐标以实现精准截图

控件截图区域不符问题解决

我在应用中实现屏幕截图功能,期望截取目标控件的完整区域(对应原红色标记截图),但实际仅截取到屏幕左上角与控件尺寸相同的区域(对应原实际截图)。

所用代码:

Private Function TakeScreenShot(ByVal Control As Control) As Bitmap

    Dim screenSize As Size = New Size(Control.Width, Control.Height)

    Dim screenGrab As New Bitmap(Control.Width, Control.Height)

    Dim g As Graphics = Graphics.FromImage(screenGrab)

    g.CopyFromScreen(New Point(Control.Location.X, Control.Location.Y), Point.Empty, screenSize)

    Return screenGrab

End Function

问题原因

Control.Location返回的是控件相对于其父容器的坐标,而CopyFromScreen方法需要的是屏幕绝对坐标。用相对坐标作为截图起始点,会导致从屏幕左上角偏移错误的位置截取,最终得到的不是目标控件的区域。

修正代码

Private Function TakeScreenShot(ByVal Control As Control) As Bitmap
    ' 获取控件在屏幕上的绝对坐标
    Dim screenLocation As Point = Control.PointToScreen(Point.Empty)
    Dim screenSize As Size = New Size(Control.Width, Control.Height)

    Dim screenGrab As New Bitmap(Control.Width, Control.Height)
    Using g As Graphics = Graphics.FromImage(screenGrab)
        ' 使用屏幕绝对坐标作为截图起始点
        g.CopyFromScreen(screenLocation, Point.Empty, screenSize)
    End Using

    Return screenGrab
End Function

关键改动说明

  • 用Control.PointToScreen(Point.Empty)获取控件左上角在屏幕上的绝对坐标,这是控件真实的屏幕位置。
  • 增加Using语句管理Graphics对象,确保资源正确释放,避免内存泄漏。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 09:22:40