问题描述
SetClipboardData
函数需要一个 HANDLE
引用;我在转换字符串以在函数中使用时遇到问题.
The SetClipboardData
function requires a HANDLE
reference; I'm having trouble converting my string for use in the function.
这是我的代码:
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?
谢谢.
推荐答案
阅读 SetClipboardData 函数.看来您错过了几个步骤并过早释放了内存.首先,你必须打电话OpenClipboard 才能使用 SetClipboardData.其次,系统拥有传递给剪贴板的内存的所有权,并且必须将其解锁.此外,内存必须是可移动的,这需要与 GlobalAlloc(而不是 LocalAlloc).
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 callOpenClipboard before you can use SetClipboardData. Secondly, the system takes ownership of the memory passed to the clipboard and it 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 = GlobalAlloc(GMEM_MOVEABLE, len);
memcpy(GlobalLock(hMem), output, len);
GlobalUnlock(hMem);
OpenClipboard(0);
EmptyClipboard();
SetClipboardData(CF_TEXT, hMem);
CloseClipboard();
这篇关于如何在C中将字符串复制到剪贴板?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!