admin管理员组

文章数量:1122832

I want to select the text of an application's input field with c++.

I have no problem selecting the text manually pressing ctrl+a on my keyboard but I am unable to do that with c++.

I thought I would get the handle of the application and simulate a ctrl+a by sending PostMessage() but I think when I send 'ctrl' it isn't being 'held down' while I send the 'a'? so the text isn't being selected. Instead I just get an 'a' in the input box.

// click in the input field
PostMessage(hwnd, WM_LBUTTONDOWN, MK_LBUTTON, MAKELPARAM(100, 100));
PostMessage(hwnd, WM_LBUTTONUP, MK_LBUTTON, MAKELPARAM(100, 100));

// select input fields text
PostMessage(hwnd, WM_KEYDOWN, VK_CONTROL, 0);
PostMessage(hwnd, WM_KEYDOWN, 'A', 0);
PostMessage(hwnd, WM_KEYUP, 'A', 0);
PostMessage(hwnd, WM_KEYUP, VK_CONTROL, 0);

I want to select the text of an application's input field with c++.

I have no problem selecting the text manually pressing ctrl+a on my keyboard but I am unable to do that with c++.

I thought I would get the handle of the application and simulate a ctrl+a by sending PostMessage() but I think when I send 'ctrl' it isn't being 'held down' while I send the 'a'? so the text isn't being selected. Instead I just get an 'a' in the input box.

// click in the input field
PostMessage(hwnd, WM_LBUTTONDOWN, MK_LBUTTON, MAKELPARAM(100, 100));
PostMessage(hwnd, WM_LBUTTONUP, MK_LBUTTON, MAKELPARAM(100, 100));

// select input fields text
PostMessage(hwnd, WM_KEYDOWN, VK_CONTROL, 0);
PostMessage(hwnd, WM_KEYDOWN, 'A', 0);
PostMessage(hwnd, WM_KEYUP, 'A', 0);
PostMessage(hwnd, WM_KEYUP, VK_CONTROL, 0);
Share Improve this question edited Nov 22, 2024 at 16:06 Jerry Coffin 489k83 gold badges648 silver badges1.1k bronze badges asked Nov 22, 2024 at 14:04 KevinKevin 314 bronze badges 1
  • 1 if this is edit control, EM_SETSEL must be used – RbMm Commented Nov 22, 2024 at 14:21
Add a comment  | 

1 Answer 1

Reset to default 1

As @RbMm said, one way to do this job is to use EM_SETSEL. The usual difficulty with using it is that you need to find the window you want to target. Since you know the specific location of the window you care about you can use WindowFromPoint to find the window. That gives you an HWND, so you just need to post an EM_SETSEL to that window.

In the more typical case where you know something about the window, but not its exact location, you're typically stuck with doing something like EnumWindows to find the top-level window of the application you care about, then EnumChildWindows to find the specific edit control you care about. You can certainly do that, but the code can get a bit...tedious.

If you prefer to continue the route you've started, synthesizing individual keystrokes instead, you need to use SendInput instead of PostMessage to do the job. You can't synthesize keyboard input with PostMessage.

本文标签: windowsHow to select the text of an application39s input field with cStack Overflow