Cut, copy, and paste using API functions

Copying and pasting text and images programmatically isn’t difficult at all, using the methods of the Clipboard object. However, implementing a generic Edit menu that copies and pastes the highlighted contents of whatever control is the selected control is often cumberson. For example, depending on the type of the active control you might need to query the SelText property (TextBox and ComboBox controls), the SelRTF property (the RichTextBox control), or the Picture property (the PictureBox control), not to mention other ActiveX controls.

A better approach is to send the proper Windows message to whatever control is the ActiveControl. For example, sending the WM_CUT message cuts the current contents to the Clipboard, regardless of the type of the control. Here are a collection of routine that encapsulate the proper call to the SendMessage API function:

Private Const WM_CUT = &H300Private Const WM_COPY = &H301Private Const WM_PASTE = &H302Private Const WM_CLEAR = &H303Private Declare Function SendMessage Lib "user32" Alias "SendMessageA" (ByVal _    hWnd As Long, ByVal wMsg As Long, ByVal wParam As Long, _    lParam As Any) As Long' Copy the contents of a control into the ClipboardSub ControlCopy(ByVal hWnd As Long)    SendMessage hWnd, WM_COPY, 0, ByVal 0&End Sub' Cut the contents of a control into the ClipboardSub ControlCut(ByVal hWnd As Long)    SendMessage hWnd, WM_CUT, 0, ByVal 0&End Sub' Paste the contents of the Clipboard into a controlSub ControlPaste(ByVal hWnd As Long)    SendMessage hWnd, WM_PASTE, 0, ByVal 0&End Sub' Delete the selected contents of a controlSub ControlDelete(ByVal hWnd As Long)    SendMessage hWnd, WM_CLEAR, 0, ByVal 0&End Sub

Share the Post:
Share on facebook
Share on twitter
Share on linkedin


Recent Articles: