67 lines
1.6 KiB
C++
Raw Normal View History

2024-01-08 23:37:00 +08:00
2024-04-02 15:36:52 +08:00
#include "define.h"
bool tryopenclipboard(HWND hwnd = 0)
{
2024-01-08 23:37:00 +08:00
bool success = false;
2024-04-02 15:36:52 +08:00
for (int i = 0; i < 50; i++)
{
if (OpenClipboard(hwnd))
{
2024-01-08 23:37:00 +08:00
success = true;
break;
}
2024-04-02 15:36:52 +08:00
else
{
2024-01-08 23:37:00 +08:00
Sleep(10);
}
}
return success;
}
2024-04-02 15:36:52 +08:00
wchar_t *clipboard_get()
{
wchar_t *data = 0;
if (tryopenclipboard() == false)
return 0;
do
{
HANDLE hData = GetClipboardData(CF_UNICODETEXT);
if (hData == 0)
break;
LPWSTR pszText = static_cast<LPWSTR>(GlobalLock(hData));
if (pszText == 0)
break;
int sz = GlobalSize(hData);
2024-01-08 23:37:00 +08:00
data = new wchar_t[sz + 1];
wcscpy_s(data, sz, pszText);
data[sz] = 0;
GlobalUnlock(hData);
} while (false);
CloseClipboard();
return data;
}
2024-04-02 15:36:52 +08:00
bool clipboard_set(HWND hwnd, wchar_t *text)
{
2024-01-08 23:37:00 +08:00
bool success = false;
2024-04-02 15:36:52 +08:00
// static HWND hwnd=CreateWindowExA(0,"STATIC",0,0,0,0,0,0,0,0,0,0);
if (tryopenclipboard(hwnd) == false)
return false;
2024-01-08 23:37:00 +08:00
EmptyClipboard();
2024-04-02 15:36:52 +08:00
do
{
2024-01-08 23:37:00 +08:00
HGLOBAL hClipboardData;
size_t len = wcslen(text) + 1;
hClipboardData = GlobalAlloc(GMEM_MOVEABLE, len * sizeof(wchar_t));
2024-04-02 15:36:52 +08:00
if (hClipboardData == 0)
break;
auto pchData = (wchar_t *)GlobalLock(hClipboardData);
if (pchData == 0)
break;
wcscpy_s(pchData, len, text);
GlobalUnlock(hClipboardData);
2024-01-08 23:37:00 +08:00
SetClipboardData(CF_UNICODETEXT, hClipboardData);
success = true;
2024-04-02 15:36:52 +08:00
2024-01-08 23:37:00 +08:00
} while (false);
CloseClipboard();
return success;
}