tags:

views:

74

answers:

1

I tried to uset IDataObject to put a some text to clipboard. But the GlobalUnlock fails. What I'm doing wrong?

IDataObject *obj;
HRESULT ret;
assert(S_OK == OleGetClipboard(&obj));

FORMATETC fmtetc = {0};
fmtetc.cfFormat = CF_TEXT;
fmtetc.dwAspect = DVASPECT_CONTENT;
fmtetc.lindex = -1;
fmtetc.tymed = TYMED_HGLOBAL;

STGMEDIUM medium = {0};
medium.tymed = TYMED_HGLOBAL;
char* str = "string";

medium.hGlobal = GlobalAlloc(GMEM_MOVEABLE+GMEM_DDESHARE, strlen(str)+1); 
char* pMem = (char*)GlobalLock(medium.hGlobal);
strcpy(pMem,str);
assert(GlobalUnlock(medium.hGlobal) != 0); // !!! ERROR
assert(S_OK == obj->SetData(&fmtetc,&medium,TRUE));
assert(S_OK == OleSetClipboard(obj));
A: 

Well, after looking at the documentation this is to be expected:

Return Value

If the memory object is still locked after decrementing the lock count, the return value is a nonzero value. If the memory object is unlocked after decrementing the lock count, the function returns zero and GetLastError returns NO_ERROR.

If the function fails, the return value is zero and GetLastError returns a value other than NO_ERROR.

So your assertion is wrong; it should be:

assert(GlobalUnlock(medium.hGlobal) == 0 && GetLastError() == NO_ERROR);
Luke
How stupid I'm, I have corrected it. But the SetData still fails. It returns E_FAIL and the GetLastError returns 0. Actually, can I use OleGetClipboard to get the interface for writting?
trudger
I finally decided to use Windows API SetClipboardData. It's easier.
trudger