这段代码的作用是将一个字符串发送到剪贴板。然而,我只能让它正常工作一次。现在当我按下CTRL+V键时,它无法正确地粘贴。
但是当我使用这个片段来识别剪贴板中的文本时,它会显示应该有的内容。
#include <windows.h>
#include <iostream>
BOOL SetClipboardText(LPCTSTR pszText)
{
BOOL ok = FALSE;
if(OpenClipboard(NULL)) {
// the text should be placed in "global" memory
HGLOBAL hMem = GlobalAlloc(GMEM_SHARE | GMEM_MOVEABLE,
(lstrlen(pszText)+1)*sizeof(pszText[0]) );
LPTSTR ptxt = (LPTSTR)GlobalLock(hMem);
lstrcpy(ptxt, pszText);
GlobalUnlock(hMem);
// set data in clipboard; we are no longer responsible for hMem
ok = (BOOL)SetClipboardData(CF_TEXT, hMem);
CloseClipboard(); // relinquish it for other windows
}
return ok;
}
int main()
{
LPCTSTR test = "DOG";
SetClipboardText(test);
return 0;
}
//get clipboard text
#include <windows.h>
#include <iostream>
#include <stdio.h>
using namespace std;
int main()
{
HANDLE clip;
if (OpenClipboard(NULL))
clip = GetClipboardData(CF_TEXT);
printf("%s",clip);
//cout << (char*)clip; // HANDLE==void*, so cast it
cin.get();}