Send Text to other Applications

2019-07-31 10:14发布

问题:

I have a string variable. Now i want to store a string value into a control in another application without using the clipboard. I wanna do it manually.

I think i should use SendMessage(WM_SETTEXT). Which way do you suggest (with an example please)?

回答1:

As your application knows the string it has to send...

You can set the focus to the target window/application if needed.

Then you process each char contained in your string to simulate their key strokes. Something like that (too basic to work exactly as you expect, but the idea is here... ;o)):

for i := 1 to Length(yourstring) do
begin
  keybd_event(Ord(yourstring[i]), 0, 0, 0);  // key down
  Sleep(10);
  keybd_event(Ord(yourstring[i]), 0, 0 or KEYEVENTF_KEYUP, 0); / key up
  Sleep(10);
end;

If your string uppercase, ..., you need to simulate the shift, ctrl, ...



回答2:

Input multiple byte characters with keybd_event:

procedure InsertText(text:string);
var i:integer;
    j:integer;
    ch:byte;
    str:string;
begin
  i:=1;
  while i<=Length(text) do
  begin
    ch:=byte(text[i]);
    if Windows.IsDBCSLeadByte(ch) then
       begin
         Inc(i);
         str:=inttostr(MakeWord(byte(text[i]), ch));
         keybd_event(VK_MENU, MapVirtualKey(VK_MENU, 0), 0, 0);
         j:=1;
         while j<=Length(str) do
         begin
               keybd_event(96+strtoint(str[j]), MapVirtualKey(96+strtoint(str[j]), 0), 0, 0);
               keybd_event(96+strtoint(str[j]), MapVirtualKey(96+strtoint(str[j]), 0), 2, 0);
               j:=j+1;
         end;
         keybd_event(VK_MENU, MapVirtualKey(VK_MENU, 0), KEYEVENTF_KEYUP, 0);
       end
    else begin
           keybd_event(VkKeyScan(text[i]),0,0,0);
           keybd_event(VkKeyScan(text[i]),0,2,0);
         end;
    Inc(i);
  end;
end;