Skip to content

Instantly share code, notes, and snippets.

@katahiromz
Created November 23, 2024 03:21
Show Gist options
  • Save katahiromz/f1a9aedc0743b2cb826a7dcec9b8c5f5 to your computer and use it in GitHub Desktop.
Save katahiromz/f1a9aedc0743b2cb826a7dcec9b8c5f5 to your computer and use it in GitHub Desktop.
Win32クリップボードテキスト
#include <windows.h>
#include <string>
// クリップボードにテキストをコピーする
BOOL CopyTextToClipboard(const std::string& text)
{
if (!OpenClipboard(hwnd))
return FALSE;
BOOL bOK = FALSE;
int cch = int(text.size() + 1);
size_t cbText = (text.size() + 1) * sizeof(char);
EmptyClipboard();
if (HANDLE hText = GlobalAlloc(GHND | GMEM_SHARE, cbText))
{
char *psz = (char *)GlobalLock(hText);
if (psz)
{
CopyMemory(psz, text.c_str(), cbText);
GlobalUnlock(hText);
bOK = SetClipboardData(CF_TEXT, hText);
if (!bOK)
GlobalFree(hText);
}
else
{
GlobalFree(hText);
}
}
CloseClipboard();
return bOK;
}
// クリップボードからテキストを取得
BOOL GetTextFromClipboard(std::string& text)
{
text.clear();
if (!IsClipboardFormatAvailable(CF_TEXT) || !OpenClipboard(hwnd))
return FALSE;
BOOL bOK = FALSE;
if (HANDLE hText = GetClipboardData(CF_TEXT))
{
if (char *psz = (char *)GlobalLock(hText))
{
text = psz;
GlobalUnlock(hText);
bOK = TRUE;
}
}
CloseClipboard();
return bOK;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment