Tuesday, July 19, 2011

Visual Basic Tips: Accessing Text and Images from the Clipboard

  
Visual Basic provides built-in objects that allow programmers to access the contents of the clipboard easily. Data format from the clipboard can be text, images, rich text, file lists, etc. But for now, I'll try showing how to access clipboard data in the form of text and images.

Accessing Text in the Clipboard

Visual Basic has provided the "Clipboard" object to access the contents of the clipboard easily.
To retrieve text from the clipboard, you could use these instructions:

Clipboard.GetText

Example:

Dim S As String

S = Clipboard.GetText
MsgBox S


While for inserting text into the clipboard, you could use the following instructions:

Clipboard.Clear
Clipboard.SetText str   'str is a String

Example:

Dim S As String

S = "test 123"
Clipboard.Clear
Clipboard.SetText S     'Clipboard now contains the text: 'tes 123'


Accessing Images in the Clipboard

To retrieve data in the form of image (bitmap) from the clipboard, use the following instructions:

Clipboard.GetData(vbCFBitmap)

Here are the examples:

Make a PictureBox control (Picture1) dan CommandButton (Command1) on the Form. Then write these codes:

'*** codes for Command1
Private Sub Command1_Click()
    If Not Clipboard.GetFormat(vbCFBitmap) Then
        MsgBox "No image in the Clipbooard !"
        Exit Sub
    End If
    Picture1.Picture = Clipboard.GetData(vbCFBitmap)
   
End Sub

Note: Before you click the Command1 button, do PrintScreen first (press the PrintScreen key on the keyboard). Then click the Command1 button. Now you shoud see the Printscreen image displayed on the Picture1 control.

--------------
And to insert the image data into the clipboard, you could use these instructions:

Clipboard.Clear
Clipboard.SetData dt, vbCFBitmap   'dt is image data

Example:

Create a PictureBox control (Picture1) and a CommandButton (Command1) on the Form. Insert any image into Picture1 through the Picture property dialog box.

'*** codes for Command1
Private Sub Command1_Click()
    Clipboard.Clear
    Clipboard.SetData Picture1.Image, vbCFBitmap
    MsgBox "Image is in the Clipboard
now"
   
End Sub

Note: To test the example above, first click the Command1 button, then open the Paint program, and then paste (press CTRL + V). If image in Picture1 appears in the Paint program, means that example works. I myself have tried it and succeeded.
         

Related Posts:

No comments: