Graphics.CopyFromScreen() 要求您指定屏幕坐标。
您可以使用Control.RectangleToScreen() 和Control.PointToScreen() 方法将本地坐标转换为屏幕坐标。
其他方法则相反,请参阅文档。
要以屏幕坐标计算控件的客户区,您可以使用其RectangleToScreen() 方法并传递ClientRectangle 属性的值:
Dim clientRectToScreen = [Control].RectangleToScreen([Control].ClientRectangle)
要包含非客户区(例如,控件的边框,包括滚动条,如果有的话),您需要其Bounds 的屏幕坐标。
有不同的方法可以做到这一点。一个简单的方法是让控件的父级获取它们,将子控件的边界传递给父级的RectangleToScreen() 方法。
如果你想打印一个Form,它是一个Top-Level Control,所以它没有Parent,直接使用它的Bounds:这些度量已经表达了屏幕坐标。
在ControlToBitmap()方法中显示:
Private Function ControlToBitmap(ctrl As Control, clientAreaOnly As Boolean) As Bitmap
If ctrl Is Nothing Then Return Nothing
Dim rect As Rectangle
If clientAreaOnly Then
rect = ctrl.RectangleToScreen(ctrl.ClientRectangle)
Else
rect = If(ctrl.Parent Is Nothing, ctrl.Bounds, ctrl.Parent.RectangleToScreen(ctrl.Bounds))
End If
Dim img As New Bitmap(rect.Width, rect.Height)
Using g As Graphics = Graphics.FromImage(img)
g.CopyFromScreen(rect.Location, Point.Empty, img.Size)
End Using
Return img
End Function
要截取控件的屏幕截图,请调用此方法,将要打印的控件传递给位图并指定是只想要其内容(客户区)还是要包含非客户区(例如,如果要打印的控件是一个窗体,则需要包括标题和边框)。
-
重要:使用Path.Combine()构建路径:
Path.Combine(audiooutputfolder, $"{imageName}.png"
如果字符串插值不可用($"{variable} other parts"),您可以将文件扩展名粘贴到文件名:
Path.Combine(audiooutputfolder, imageName & ".png")
' Get the screenshot, client area only
Dim controlImage = ControlToBitmap(RichTextBox2, True)
' Save the image to the specified Path using the default PNG format
controlImage.Save(Path.Combine(audiooutputfolder, $"{imageName}.png"), ImageFormat.Png)
' [...] when done with the bitmap
controlImage.Dispose()
旁注:
如果您的应用不是 DpiAware,您可能会得到错误的屏幕坐标。
See these notes 关于这个。