C++ 获取鼠标选中文本 - 跨窗口获取选中内容
#include <Windows.h>
std::wstring GetSelectedText() { HWND hwnd = GetForegroundWindow(); DWORD pid; DWORD tid = GetWindowThreadProcessId(hwnd, &pid);
// Attach the thread to the current thread
AttachThreadInput(GetCurrentThreadId(), tid, TRUE);
// Get the focus control handle
HWND focusHwnd = GetFocus();
// Detach the thread
AttachThreadInput(GetCurrentThreadId(), tid, FALSE);
// Get the length of the text
int length = SendMessageW(focusHwnd, WM_GETTEXTLENGTH, 0, 0);
// Allocate memory for the text
wchar_t* buffer = new wchar_t[length + 1];
// Get the text
SendMessageW(focusHwnd, WM_GETTEXT, length + 1, (LPARAM)buffer);
std::wstring selectedText(buffer);
delete[] buffer;
return selectedText;
}
这个方法将返回当前焦点窗口中选中的文本。您可以将其封装到一个类或函数中以进行更方便的使用。
AI 优化版
原文地址:https://www.cveoy.top/t/topic/ouq7 著作权归作者所有。请勿转载和采集!