As you should be getting the length of the string from a call to string::length (or strlen) the exact string used is irrelevent. And as the basic clipboard functionality has not changed for years, the Windows version should not matter.
The version of the source you linked to has other problems, as already mentioned. The version helios points to above is pretty much what I'd do, formatting aside, except for the change from s.size() to s.size()+1 and the OpenClipboard() call's parameter.
I usually call
OpenClipboard(hwnd);
-- with the call of my app's main window. I have now checked this on MSDN and while NULL (or 0) is an acceptable parameter value, the comments for this call state:
If an application calls OpenClipboard with hwnd set to NULL, EmptyClipboard sets the clipboard owner to NULL; this causes SetClipboardData to fail. |
As EmptyClipboard() is being called here, you should avoid the use of a NULL window handle.
Depending on how defensive you want to be, you could check that the call to OpenClipboad succeeds. This would only fail if another application didn't successfully close the clipboard after use, leaving it locked.
Andy
1 2 3 4 5 6 7 8 9 10 11 12 13 14
|
void toClipboard(HWND hwnd, const std::string &s){
OpenClipboard(hwnd);
EmptyClipboard();
HGLOBAL hg=GlobalAlloc(GMEM_MOVEABLE,s.size()+1);
if (!hg){
CloseClipboard();
return;
}
memcpy(GlobalLock(hg),s.c_str(),s.size()+1);
GlobalUnlock(hg);
SetClipboardData(CF_TEXT,hg);
CloseClipboard();
GlobalFree(hg);
}
|
P.S. There are other minor details you might see in similar code:
- OpenClipboard(NULL); -- the same, as NULL == 0
- GHND rather than GMEM_MOVEABLE -- GHND == GMEM_MOVEABLE | GMEM_ZEROINIT (I wouldn't use GHND here as the allocated buffer is being completely filled by memset
- some form of string copy rather than memcpy (here you know the length of the string, so memcpy makes more sense)