Home
Search
 
What's New
Index
Books
Links
Q & A
Newsletter
Banners
 
Feedback
Tip Jar
 
C# Helper...
 
XML RSS Feed
Follow VBHelper on Twitter
 
 
 
MSDN Visual Basic Community
 
 
 
 
 
TitleCopy, cut, and paste pieces of a picture
Description
Keywordscopy, cut, paste, Clipboard, image, picture, piece, section, area, region
CategoriesTips and Tricks, Graphics
 
To copy a piece of a picture to the Clipboard, use PaintPicture to copy the piece to a hidden PictureBox. Then use the clipboard object's Clear and SetData methods to copy the picture.

To paste a piece of a picture, use the Clipboard's GetData method to get the image and paste it into a hidden PictureBox. Then use PaintPicture to copy it where you want it.

In this program, uUse the left mouse button to click and drag to select an area in a picture. Right click on a picture to get a context menu allowing Copy, Cut, and Paste. Pastes puts the picture in the upper left corner of the area selected.

To learn more about graphics in Visual Basic, see my book Visual Basic Graphics Programming.

 
' Copy the selected region to the clipboard.
Private Sub mnuCopy_Click()
    ' Make sure X1 <= X2 and Y1 <= Y2.
    OrderCorners

    ' Copy the selected area into picTemp.
    picTemp.Width = X2(SelPic) - X1(SelPic) + 1
    picTemp.Height = Y2(SelPic) - Y1(SelPic) + 1
    picTemp.PaintPicture _
        picCanvas(SelPic).Picture, _
        0, 0, X2(SelPic) - X1(SelPic) + 1, Y2(SelPic) - _
            Y1(SelPic) + 1, _
        X1(SelPic), Y1(SelPic), X2(SelPic) - X1(SelPic) + _
            1, Y2(SelPic) - Y1(SelPic) + 1

    ' Copy to the clipboard.
    Clipboard.Clear
    Clipboard.SetData picTemp.Image, vbCFBitmap
End Sub

Private Sub mnuCut_Click()
    ' Copy the picture to the clipboard.
    mnuCopy_Click
    
    ' Erase this part of the image.
    picCanvas(SelPic).Line _
        (X1(SelPic), Y1(SelPic))-(X2(SelPic), Y2(SelPic)), _
        picCanvas(SelPic).BackColor, BF
End Sub


' Paste whatever is in the clipboard at (X1, Y1).
Private Sub mnuPaste_Click()
    ' Make sure an image exists. This will happen
    ' if the clipboard does not contain a bitmap
    ' and the user presses ^V.
    If Not Clipboard.GetFormat(vbCFBitmap) Then Exit Sub
    
    ' Make sure X1 <= X2 and Y1 <= Y2.
    OrderCorners
    
    picTemp.AutoSize = True
    picTemp.Picture = Clipboard.GetData(vbCFBitmap)
    picTemp.AutoSize = False

    picCanvas(SelPic).PaintPicture _
        picTemp.Picture, _
        X1(SelPic), Y1(SelPic), _
        picTemp.ScaleWidth, picTemp.ScaleHeight, _
        0, 0, picTemp.ScaleWidth, picTemp.ScaleHeight

    ' Make the picture part of the background.
    picCanvas(SelPic).Picture = picCanvas(SelPic).Image
End Sub
 
Formatted by Neil Crosby
 
 
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated