Feature: Support replacing clip text via keyboard management dialog
This commit is contained in:
@@ -84,4 +84,41 @@ namespace clip {
|
||||
LeaveCriticalSection(&GetClipLock());
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 将 UTF-8 字符串安全地设置到 Windows 剪切板
|
||||
*/
|
||||
inline bool set_text_utf8(const std::string& utf8_str) {
|
||||
if (utf8_str.empty()) return false;
|
||||
|
||||
// 1. 将 UTF-8 转换为 UTF-16 (因为 Windows 剪切板原生支持 UTF-16)
|
||||
int wlen = MultiByteToWideChar(CP_UTF8, 0, utf8_str.c_str(), -1, NULL, 0);
|
||||
if (wlen <= 0) return false;
|
||||
|
||||
// 2. 分配全局内存
|
||||
HGLOBAL hMem = GlobalAlloc(GMEM_MOVEABLE, wlen * sizeof(wchar_t));
|
||||
if (!hMem) return false;
|
||||
|
||||
// 3. 执行转换并锁定内存
|
||||
wchar_t* pMem = (wchar_t*)GlobalLock(hMem);
|
||||
MultiByteToWideChar(CP_UTF8, 0, utf8_str.c_str(), -1, pMem, wlen);
|
||||
GlobalUnlock(hMem);
|
||||
|
||||
// 4. 操作剪切板
|
||||
bool success = false;
|
||||
if (OpenClipboard(NULL)) {
|
||||
EmptyClipboard();
|
||||
if (SetClipboardData(CF_UNICODETEXT, hMem)) {
|
||||
success = true;
|
||||
}
|
||||
CloseClipboard();
|
||||
}
|
||||
|
||||
// 如果 SetClipboardData 失败,需要手动释放内存;成功则由系统接管
|
||||
if (!success) {
|
||||
GlobalFree(hMem);
|
||||
}
|
||||
|
||||
return success;
|
||||
}
|
||||
} // namespace clip
|
||||
|
||||
Reference in New Issue
Block a user