WHCSRL 技术网

C++操作剪贴板

设置剪贴板

	std::string  TempBin = "123";
    HGLOBAL hMemBin = NULL;
    PCHAR   LockBin = NULL;
    OpenClipboard(NULL);
    EmptyClipboard();
    hMemBin = GlobalAlloc(GMEM_MOVEABLE, TempBin.size() + 1);
    LockBin = (PCHAR)GlobalLock(hMemBin);
    RtlMoveMemory(LockBin, TempBin.c_str(), TempBin.size() + 1);
    GlobalUnlock(hMemBin);
    LockBin = NULL;
    SetClipboardData(CF_TEXT, hMemBin);
    CloseClipboard();
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

这样,剪贴板的内容就设置成"123"了。

获取剪贴板

	HGLOBAL hMemBin = NULL;
    PCHAR   LockBin = NULL;
    PCHAR   TempBin = NULL;
    OpenClipboard(NULL);
    hMemBin = GetClipboardData(CF_TEXT);
    LockBin = (PCHAR)GlobalLock(hMemBin);
    TempBin = (PCHAR)malloc(GlobalSize(hMemBin));
    if (TempBin != NULL)
    {
        RtlMoveMemory(TempBin, LockBin, GlobalSize(hMemBin));
    }
    GlobalUnlock(hMemBin);
    LockBin = NULL;
    CloseClipboard();
    printf("%%s", TempBin);
    if (TempBin != NULL)
    {
        free(TempBin);
        TempBin = NULL;
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20

TempBin里保存的就是剪贴板的内容,注意用完要释放内存。

推荐阅读