How to get selected text from another application?

I get selected text from another application without using the clipboard. I found a way to have HWND from the active application, but when I use EM_GETSELTEXT, they are not text in the buffer.

 char* shortcut::getSelectedText(){
  POINT mouse;
  if (GetCursorPos(&mouse)){
  HWND window = WindowFromPoint(mouse);//get the HWND from the active application
    if (window != nullptr){
        char* buffer = new char[100];
        SendMessage(window , EM_GETSELTEXT, 0, LPARAM(buffer));
        return buffer;  
    }
    else{
        return "";
    }
  }
  else{
    return "";
  }
}
+4
source share
1 answer

You can do this in two steps. First send EM_GETSEL to get the start / end indices of the selected text (0,0 if nothing is selected) Then call GetWindowText or send WM_GETTEXT to get the full text and filter the selected substring

TCHAR buffer[100];

DWORD start, end;
SendMessage(hEdit, EM_GETSEL, (WPARAM)&start, (LPARAM)&end);

GetWindowText(hEdit, buffer, 100);
TCHAR * otherBuff = new TCHAR[100];
memset(otherBuff, 0, 100 * sizeof *otherBuff);
_tcsncpy(otherBuff, buffer + start, end);

In this case, there will be an error in your code:

You dynamically allocate a buffer and return a pointer from a function

char * buffer = new char [100];

- [] . - , "". . , . .

-1

Source: https://habr.com/ru/post/1589177/


All Articles