procedure TFrm_main.SendStringToActiveApp(Received : string);
var Tid : Cardinal;
TidTo : Cardinal;
begin
Tid:=GetCurrentThreadId;
TidTo:=GetWindowThreadProcessId(GetForeGroundWindow);
AttachThreadInput(TidTo,Tid,True);
SendKeysToHwnd(GetFocus,Received);
AttachThreadInput(TidTo,Tid,False);
end;
procedure SendKeysTohWnd(hWnd : LongWord; Text : string);
// send keystrokes to a specific window handle
var i : integer;
c : char;
wparam,
lparam : longword;
scancode : byte;
oemScan : word;
prevchar : word;
Len : word;
begin
if Text <> '' then
begin
Len:=length(Text);
i:=1;
while i <= Len do
begin
c:=Text[i];
wparam:=ord(c);
// if character is #0 then next chars will be only keydown
// if char is #1 then next chars will only be keyup
if wparam < 2 then
begin
// #0 or #1
Inc(i);
if i > Len then Exit; // prevent critical error
c:=Text[i];
prevchar:=wparam;
wparam:=ord(c);
end
else prevchar:=wparam;
if (c > #31) and (PrevChar > 1) then // only do wm_char if keyup,keydown control chars are not used
begin
// normal chars, use WM_CHAR message to simulate keystroke
oemScan:=Lobyte(vkKeyScan(c));
scancode:=MapVirtualKey(oemScan,0);
lparam:=1+(scancode shl 16);
postmessage(hwnd,WM_CHAR,wparam,lparam);
end
else
begin
// system codes, use WM_KEYDOWN and WM_KEYUP to simulate keystroke
scancode:=MapVirtualKey(wparam,0);
if prevchar <> 1 then
begin
lparam:=1 or (scancode shl 16) or $40000000; // (1 shl 30);
postmessage(hwnd,WM_KEYDOWN,wparam,lparam);
end;
if prevchar > 1 then
begin
oemScan:=Lobyte(vkKeyScan(c));
scancode:=MapVirtualKey(oemScan,0);
lparam:=1+(scancode shl 16);
postmessage(hwnd,WM_CHAR,wparam,lparam);
end;
if prevchar <> 0 then
begin
lparam:=1 or (scancode shl 16) or $C0000000; // 3 shl 30
postmessage(hwnd,WM_KEYUP,wparam,lparam);
end;
end;
Inc(i);
end;
end;
end;