views:

1037

answers:

3

The SetClipboardData function requires a HANDLE reference; I'm having trouble converting my string for use in the function.

Here is my code:

char* output = "Test";
HLOCAL hMem =  LocalAlloc( LHND,1024);
char* cptr = (char*) LocalLock(hMem);
memcpy( cptr, output, 500 );
SetClipboardData(CF_TEXT, hMem);
LocalUnlock( hMem );
LocalFree( hMem );
CloseClipboard();

What am I doing wrong here and what's the proper way to do it?

Thanks.

A: 

Take a look at Microsoft's Documentation on using the clipboard. This requires that your using the WinAPI, but this shouldn't be a problem since your on Windows. Note that programming the Windows API is never simple unless you use a very high-level language.

Lucas McCoy
Well,I've already looked at that, and came up with the code which doesn't work.
You might just try copying the exact code and see if it works. Then you can go from there.
Lucas McCoy
+5  A: 

Read the MSDN documentation for the SetClipboardData function. It appears you are missing a few steps and releasing the memory prematurely. First of all, you must call OpenClipboard before you can use SetClipboardData. Secondly, the system takes ownership of the memory passed to the clipboard and in must be unlocked. Also, the memory must be movable, which requires the GMEM_MOVEABLE flag as used with GlobalAlloc (instead of LocalAlloc).

const char* output = "Test";
const size_t len = strlen(output) + 1;
HGLOBAL hMem =  GloalAlloc(GMEM_MOVEABLE, len);
memcpy(GlobalLock(hMem), output, len);
GlobalUnlock(hMem);
OpenClipboard(0);
EmptyClipboard();
SetClipboardData(CF_TEXT, hMem);
CloseClipboard();
Judge Maygarden
That works! There's a typo on the third line.
A: 
TCHAR text[128];
.....
VERIFY(::OpenClipboard(0));
VERIFY(::EmptyClipboard());

// Calculate number of bytes to be written (includes '\0' terminator)
const int nBytes = ( _tcslen(text) + 1 ) * sizeof(TCHAR);
// Allocate global memory
HGLOBAL hMem = ::GlobalAlloc(GMEM_MOVEABLE, nBytes);
// Get a pointer to the memory
LPVOID pMem = ::GlobalLock(hMem);

CopyMemory(pMem, text, nBytes);
GlobalUnlock(hMem);
SetClipboardData(CF_TEXT, hMem);      

VERIFY(::CloseClipboard());
adatapost
That's C++ not C.
Lucas McCoy