#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;

}

这个方法将返回当前焦点窗口中选中的文本。您可以将其封装到一个类或函数中以进行更方便的使用。

C++ 获取鼠标选中文本 - 跨窗口获取选中内容