Setting the clipboard text

Windows specific questions.
Post Reply
xbgtc
Posts: 249
Joined: Oct 14, 2007 5:40
Location: Australia

Setting the clipboard text

Post by xbgtc »

How do you set the clip board text?

I see this function for getting the text

Code: Select all

Function get_clipboard() As String
        If IsClipboardFormatAvailable(CF_TEXT) = 0 Then Return "Error"
        If OpenClipboard(0) = 0 Then Return "Error"
        Function = *Cast(zstring Ptr,GetClipboardData(CF_TEXT))
        CloseClipboard()
End Function
dim as string s=get_clipboard
print s
sleep
How can it be changed to SET some text?
SARG
Posts: 1755
Joined: May 27, 2005 7:15
Location: FRANCE

Re: Setting the clipboard text

Post by SARG »

A code I keep with other snippets :-)
Many comments so it's easy to understand.

Code: Select all

'Send text to clipboard with api calls
'by Dennis McKinney

#Include Once "windows.bi"

Function ClipboardSetText(hOwner As handle, strText As string) As handle
'Puts some text on the Windows clipboard
'In: The text to place on the clipboard
'Out: 0 if fail, > 0 if text placed on clipboard

strText = strText + chr$(0)
Var lngSize = Len(strText)
Var hMemory = GlobalAlloc(GMEM_MOVEABLE, lngSize)

'Lock the object into memory
Var lpMemory = GlobalLock(hMemory)

'Move the string into the memory we locked
Var ret=RtlMoveMemory(lpMemory, StrPtr(strText), lngSize)

'Don't send clipboard locked memory.
Var r = GlobalUnlock(hMemory)

'Open the clipboard
r=OpenClipboard( hOwner)

'Remove the current contents of the clipboard
r=EmptyClipboard

'Add our string to the clipboard as text
'If hSuccess > 0 then we have set the clipboard data
Var hSuccess=SetClipboardData( CF_TEXT, hMemory)

'Close the clipboard
r=CloseClipboard

'If we have set the clipboard data, we no longer own
'the memory--Windows does, so don't free it unless we failed.
If hSuccess = 0 Then
 GlobalFree(hMemory)
End If

ClipboardSetText = hSuccess
End Function


'Note: You can use your window handle here instead of 0
Var r = ClipboardSetText(0, "Hello World")
'If r is > 0 then the text has been placed on the clipboard
End
xbgtc
Posts: 249
Joined: Oct 14, 2007 5:40
Location: Australia

Re: Setting the clipboard text

Post by xbgtc »

Yep commented well and works great! - thanks SARG!
Post Reply