C++ 获取鼠标选中文本 (非复制内容)
#include <Windows.h>
#include
char* GetSelectedText() { HWND hWnd = GetForegroundWindow(); // 获取当前激活的窗口句柄 DWORD processId; DWORD threadId = GetWindowThreadProcessId(hWnd, &processId); // 获取该窗口的线程ID和进程ID if (threadId != GetCurrentThreadId()) // 如果该窗口的线程ID不是当前线程ID,则将该线程附加到当前线程 { AttachThreadInput(GetCurrentThreadId(), threadId, TRUE); } HWND hFocusWnd = GetFocus(); // 获取焦点控件的句柄 if (threadId != GetCurrentThreadId()) // 如果该控件的线程ID不是当前线程ID,则将该线程附加到当前线程 { AttachThreadInput(GetCurrentThreadId(), GetWindowThreadProcessId(hFocusWnd, nullptr), TRUE); } const int BUFFER_LENGTH = 1024; WCHAR buffer[BUFFER_LENGTH]; SendMessageW(hFocusWnd, WM_GETTEXT, BUFFER_LENGTH, (LPARAM)buffer); // 发送获取文本的消息 std::wstring wideStr(buffer); std::string str(wideStr.begin(), wideStr.end()); // 将宽字符串转换为窄字符串 char* result = new char[str.length() + 1]; strcpy_s(result, str.length() + 1, str.c_str()); // 将窄字符串复制到新的字符数组中 return result; }
AI 优化版
原文地址:https://www.cveoy.top/t/topic/ourK 著作权归作者所有。请勿转载和采集!