We help IT Professionals succeed at work.

Check out our new AWS podcast with Certified Expert, Phil Phillips! Listen to "How to Execute a Seamless AWS Migration" on EE or on your favorite podcast platform. Listen Now


An easy one: CString to clipboard

MelissaC asked
Medium Priority
Last Modified: 2008-02-01
Here's an easy 30 points for you experts:

I need to put a CString on the clipboard (without using OLE, if possible) , but I can't find the appropriate syntax.
The code's like this:

      CString str="I'm on the clipboard!!!";
      SetClipboardData( CF_TEXT ??, hData ??? ) // This line is the problem

Does anybody know how to do this? (Please reply with code...)
Watch Question

From the help On SetClipboard I would try somthing like
HANDLE MemHandle;
char *memptr
unsigned int StrLen;
StrLen = (str.GetLength()+1) * sizeof( TCHAR );
MemHandle = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, StrLen);
memptr = GlobalLock( MemHandle );
ASSERT( memptr );
memset( memptr, 0, StrLen );
memcpy( memptr, (char*)(LPCTSTR)str );
GlobalUnlock( MemHandle )
SetClipboardText( CF_TEXT, MemHandle );

GlobalAlloc() a memory block with the GMEM_MOVEABLE and GMEM_DDESHARE flags. GlobalLock() it and CopyMemory() the CString into the memory and GlobalUnlock() it. Then pass the handle returned by GlobalAlloc() as hData.

Oops, I didn't see Andy Keys's comment. He provided you with the code. You may reject mine and accept Andy Keys's.

Regarding Andy Keys's code, StrLen = (str.GetLength()+1) * sizeof( TCHAR );

I think * sizeof( TCHAR ) is not needed because CString::GetLength returns a count of the bytes in the string rather than a count of the characters.


Sorry, Chensu. You're real helpful but I needed some code to insert in my program. I tried Andy Keys' code and it worked (with some alterations). Andy, if you propose an answer with your code, you've gained 30 points!
Thanks both of you!
Unlock this solution with a free trial preview.
(No credit card required)
Get Preview
Unlock the solution to this question.
Thanks for using Experts Exchange.

Please provide your email to receive a free trial preview!

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.


Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.