具体简洁、优化的代码请看Windows截图 (VB.net,使用鼠标任意方向的截图,类库——9)
VB.net用screen类来截图,其实不需要调用api
在类库myScreen里写函数
''' <summary>
''' 获取屏幕图片
''' </summary>
''' <returns>屏幕图片</returns>
Public Function GetScreen()
Dim scr As Screen = Screen.PrimaryScreen
Dim recSc As Rectangle = scr.Bounds
Image = New Bitmap(recSc.Width, recSc.Height)
g = Graphics.FromImage(Image)
g.CopyFromScreen(New Point(0, 0), New Point(0, 0), New Size(recSc.Width, recSc.Height))
Return Image
End Function
''' <summary>
''' 此函数多用来裁剪获取到的屏幕图片。注意:调用时要先在MouseDown中向GDIscr.p1中传入第一个顶点。
''' 再在MouseUp中向GDIscr.p2传入第二个顶点,顶点样式为从左上角划向右下角。
''' </summary>
''' <param name="bmp">传入截图,也可是其他的图片</param>
''' <returns>裁剪后的图片</returns>
Public Function CutScren(bmp As Bitmap)
g = Graphics.FromImage(bmp)
Dim rc As Rectangle = New Rectangle(p1, New Size(p2.X - p1.X, p2.Y - p1.Y)) '起点和长宽
Image = bmp.Clone(rc, Imaging.PixelFormat.Format32bppArgb)
Return Image
End Function
在类中写:
Public p1 As Point
Public p2 As Point
公开这两个变量:在主窗体需要调用
调用:test里新建一个窗体叫Cut
加入一个picturebox:
FromBorderStyle改为none
WindowState改为Maximized,
Cut写入代码:
'Imports GDI_Make_NET4_5.myScreen
Public Class Cut
Public GDIscr As New GDI_Make_NET4_5.myScreen
Private ispick As Boolean
Public Sub ShowMe(bmp As Bitmap)
Pic.Location = New Point(0, 0)
Pic.Width = bmp.Width
Pic.Height = bmp.Height
Pic.Image = bmp
ispick = True
Me.Show()
End Sub
Private Sub Pic_MouseDown(sender As Object, e As MouseEventArgs) Handles Pic.MouseDown
If ispick = True Then
GDIscr.p1 = New Point(e.X, e.Y)
End If
End Sub
Private Sub Pic_MouseUp(sender As Object, e As MouseEventArgs) Handles Pic.MouseUp
If ispick = True Then
GDIscr.p2 = New Point(e.X, e.Y)
Pic.Image = GDIscr.CutScren(Pic.Image)
Clipboard.SetImage(Pic.Image)
MsgBox("已复制到剪切板,双击图片退出")
ispick = False
End If
End Sub
Private Sub Pic_DoubleClick(sender As Object, e As EventArgs) Handles Pic.DoubleClick
Close()
End Sub
End Class
主窗体用MouseDown获取第一个点,MouseUp获取第二个点并调用函数,传入myScreen,
ispick的作用是防止二次裁剪出现错误,代码中的msgbox段可以自行修改、或保存图片。
测试:
点screen则获取当前屏幕的截图
点击cut显示Cut窗体,注意,显示一个窗体。选择第一个点是你想选择区域的左上角,第二个点是你想选择区域的右下角,看懂代码就可以了,如果把点的顺序反过来截图,则显示不出。