C++ 获取鼠标选中文本 (UTF-8 编码)
在 Windows 平台,可以使用以下 C++ 代码实现获取鼠标选中的数据:
#include <Windows.h>
#include <string>
std::string GetSelectedText()
{
HWND hWnd = GetForegroundWindow();
if (hWnd == NULL)
{
return "";
}
DWORD processId;
GetWindowThreadProcessId(hWnd, &processId);
if (processId == GetCurrentProcessId())
{
return "";
}
if (!AttachThreadInput(GetCurrentThreadId(), processId, TRUE))
{
return "";
}
HWND focusWnd = GetFocus();
if (focusWnd == NULL)
{
return "";
}
const int MAX_TEXT_LEN = 1024;
wchar_t text[MAX_TEXT_LEN] = { 0 };
SendMessageW(focusWnd, WM_GETTEXT, MAX_TEXT_LEN, (LPARAM)text);
std::wstring wstr(text);
std::string str;
int len = WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(), -1, NULL, 0, NULL, NULL);
if (len > 0)
{
char* buffer = new char[len];
WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(), -1, buffer, len, NULL, NULL);
str = buffer;
delete[] buffer;
}
AttachThreadInput(GetCurrentThreadId(), processId, FALSE);
return str;
}
该方法返回一个字符串,该字符串为选中的文本内容,编码为 UTF-8。可以在 Node.js 中使用 node-ffi 模块来调用该方法并包装成 Node.js 模块。
AI 优化版
原文地址:https://www.cveoy.top/t/topic/our2 著作权归作者所有。请勿转载和采集!