Wednesday, April 21, 2010

Visual Basic Tip: Accessing Text and Images in the Clipboard

Visual Basic provides innate objects that allow the programmer to access the contents of clipboard, either take the contents of the clipboard or insert data into the clipboard, easily. Data format which can be accessed from the clipboard can be text, images, rich text, file list, etc, can all be accessed through Visual Basic. In this page, provided tips to access data in the form of text and images from the clipboard using Visual Basic.

Accessing Text in the Clipboard

Visual Basic has provided the Clipboard object to access the contents of the clipboard with ease.
To retrieve the text from the clipboard, use the instructions:

Clipboard.GetText

Example:

Dim S As String

S = Clipboard.GetText
MsgBox S


While to insert text into the clipboard, can be used 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     'now clipboard contains text: 'test 123'


Accessing Images in the Clipboard

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

Clipboard.GetData(vbCFBitmap)

Example:

Create a PictureBox control (Picture1) and CommandButton (Command1) to the Form.

'*** codes for Command1
Private Sub Command1_Click()
    If Not Clipboard.GetFormat(vbCFBitmap) Then
        MsgBox "No image in 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 button on your keyboard). Printscreen image will be displayed on top of Picture1 control.

--------------
To insert the image-formatted data into the clipboard, use these instructions:

Clipboard.Clear
Clipboard.SetData dt, vbCFBitmap   'dt is image-formatted data,
                                   'may use 
object of IPictureDisp

Example:

Here we will insert an image that already exist in the PictureBox to the clipboard.
Create a PictureBox control (Picture1) and CommandButton (Command1) to the Form. Insert any image through the Picture property of Picture1.

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

Note: To test the example above, after you click the Command1 button, open the Paint program of Windows, and Paste (CTRL + V). If the image in Picture1 appears on the Paint program, means the examples above work. I myself have tried it and succeeded.

Related Posts:

No comments:

Post a Comment