jma*_*erx 2 c++ clipboard winapi
我有一些代码要复制和粘贴:
void WinClipboard::copy( const std::string& input )
{
LPWSTR lptstrCopy;
HGLOBAL hglbCopy;
std::wstring text;
text = _winUTF8ToUTF16(input);
// Open the clipboard, and empty it.
if (!OpenClipboard(NULL))
return;
EmptyClipboard();
// Allocate a global memory object for the text.
hglbCopy = GlobalAlloc(GMEM_MOVEABLE,
((text.length() + 1) * sizeof(WCHAR)));
if (hglbCopy == NULL)
{
CloseClipboard();
return;
}
// Lock the handle and copy the text to the buffer.
lptstrCopy = (LPWSTR)GlobalLock(hglbCopy);
memcpy(lptstrCopy, text.c_str(),
(text.length() + 1) * sizeof(WCHAR) );
lptstrCopy[(text.length() + 1) * sizeof(WCHAR)] = (WCHAR) 0; // null character
GlobalUnlock(hglbCopy);
// Place the handle on the clipboard.
SetClipboardData(CF_UNICODETEXT, hglbCopy);
// Close the clipboard.
CloseClipboard();
}
std::string WinClipboard::paste()
{
HGLOBAL hglb;
LPWSTR lptstr;
std::string result;
std::wstring input;
// get the clipboard text.
if (!IsClipboardFormatAvailable(CF_UNICODETEXT))
return result;
if (!OpenClipboard(NULL))
return result;
hglb = GetClipboardData(CF_UNICODETEXT);
if (hglb != NULL)
{
lptstr = (LPWSTR)GlobalLock(hglb);
if (lptstr != NULL)
{
GlobalUnlock(hglb);
input = lptstr;
result = _winUTF16ToUTF8(input);
}
CloseClipboard();
}
return result;
}
Run Code Online (Sandbox Code Playgroud)
它工作得很好,除了当我快速执行CTRL C然后CTRL-V(基本上调用上面的复制和粘贴函数)时,整个应用程序冻结.
我忘记检查某些内容或忘记发布资源了吗?
我在你的paste()函数中看到两个问题:
1)GlobalUnlock()在将剪贴板数据分配给std::wstring变量之前调用它.您需要撤消这些操作 - GlobalUnlock()复制数据后调用,而不是之前调用.
2)CloseClipboard()如果GetClipboardData()失败则不会打电话.