Copy Unicode Text to Clipboard

MSDN: Windows Clipboard API

$SAMPLECODE$

* Copy Unicode text into Clipboard
FUNCTION CopyUnicodeText2Clipboard(tcUnicodeText)
LOCAL lnDataLen, lcDropFiles, llOk, i, lhMem, lnPtr, lcUnicodeText
#DEFINE CF_UNICODETEXT  13
 
*  Global Memory Variables with Compile Time Constants
#DEFINE GMEM_MOVABLE 	0x0002
#DEFINE GMEM_ZEROINIT	0x0040
#DEFINE GMEM_SHARE		0x2000
 
* Load required Windows API functions
=LoadApiDlls()
 
llOk = .T.
lcUnicodeText = tcUnicodeText + CHR(0)+CHR(0)
lnDataLen = LEN(lcUnicodeText)
* Copy Unicode text into the allocated memory
lhMem = GlobalAlloc(GMEM_MOVABLE+GMEM_ZEROINIT+GMEM_SHARE, lnDataLen)
lnPtr = GlobalLock(lhMem)
=CopyFromStr(lnPtr, @lcUnicodeText, lnDataLen)
=GlobalUnlock(lhMem)
* Open clipboard and store Unicode text into it
llOk = (OpenClipboard(0) <> 0)
IF llOk
	=EmptyClipboard()
	llOk = (SetClipboardData(CF_UNICODETEXT, lhMem) <> 0)
	* If call to SetClipboardData() is successful, the system will take ownership of the memory
	*   otherwise we have to free it
	IF NOT llOk
		=GlobalFree(lhMem)
	ENDIF
	* Close clipboard
	=CloseClipboard()
ENDIF
RETURN llOk
 
FUNCTION LoadApiDlls
*  Clipboard Functions
DECLARE LONG OpenClipboard IN WIN32API LONG HWND
DECLARE LONG CloseClipboard IN WIN32API
DECLARE LONG EmptyClipboard IN WIN32API
DECLARE LONG SetClipboardData IN WIN32API LONG uFormat, LONG hMem
*  Memory Management Functions
DECLARE LONG GlobalAlloc IN WIN32API LONG wFlags, LONG dwBytes
DECLARE LONG GlobalFree IN WIN32API LONG HMEM
DECLARE LONG GlobalLock IN WIN32API LONG HMEM
DECLARE LONG GlobalUnlock IN WIN32API LONG HMEM
DECLARE LONG RtlMoveMemory IN WIN32API As CopyFromStr LONG lpDest, String @lpSrc, LONG iLen
RETURN

Comments

Thanks a lot, friend!

This is just excellent. Could you please provide vice-versa solution. I want to use Unicode text pasted in clipboard

You can use GetClipboardData(CF_UNICODETEXT) API similar to https://www.berezniker.com/content/pages/visual-foxpro/retrieve-html-cli...

Dear Sir,
Thanks a lot for the help. I am able to get Clipboard contents (Unicode) to binary but
the strings terminates when it encounters CHR(0) (which is actually a space separator in Unicode)
Therefore, a Unicode string which contains two words comes as only first word. Please help.
Thanks in advance

Add new comment

Filtered HTML

  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.
  • Web page addresses and e-mail addresses turn into links automatically.

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.