Quantcast
Channel: Delphi Forum - Delphi Programming Kings of Code - Delphi Programming
Viewing all articles
Browse latest Browse all 173

Send a character or String to your application

$
0
0
This procedure sends charaters to your application as if typed on the keyboard

Uses System.SysUtils;

procedure SendKeyString(Text: string);
var
   i: Integer;
   Shift: Boolean;
   vk, ScanCode: Word;
   ch: Char;
   c, s: Byte;
const
   vk_keys: array[0..10] of Byte = (VK_RETURN, VK_HOME, VK_END, VK_UP, VK_DOWN, VK_LEFT, VK_RIGHT, VK_PRIOR, VK_NEXT, VK_INSERT, VK_DELETE);
   vk_shft: array[0..2] of Byte = (VK_SHIFT, VK_CONTROL, VK_MENU);
   flags: array[False..True] of Integer = (KEYEVENTF_KEYUP, 0);
begin
   Shift := False;
   for i := 1 to Length(Text) do begin
      ch := Text;
      if ch >= #250 then begin
         s := Ord(ch) - 250;
         Shift := not Odd(s);
         c := vk_shft[s shr 1];
         ScanCode := MapVirtualKey(c, 0);
         Keybd_Event(c, Scancode, Flags[shift], 0);
      end else begin
         vk := 0;
         if ch >= #240 then
            c := vk_keys[Ord(ch) - 240]
         else if ch >= #228 then //228 (F1) => $70 (vk_F1)
            c := Ord(ch) - 116
         else if ch < #110 then
            c := Ord(ch)
         else begin
            vk := VkKeyScan(ch);
            c := LoByte(vk);
         end;
         ScanCode := MapVirtualKey(c, 0);
         if not Shift and (Hi(vk) > 0) then // $2A = scancode of VK_SHIFT
            Keybd_Event(VK_SHIFT, $2A, 0, 0);
         Keybd_Event(c, scancode, 0, 0);
         Keybd_Event(c, scancode, KEYEVENTF_KEYUP, 0);
         if not Shift and (Hi(vk) > 0) then
            Keybd_Event(VK_SHIFT, $2A, KEYEVENTF_KEYUP, 0);
      end;
   end;

Usage :
     SendKeyString(Chr(VK_RETURN)) or SendKeyString(Chr(13)); will send an enter to your application 
     SendKeyString(Chr(VK_ESCAPE)) or SendKeyString(Chr(27)); will send an escape to  the application
     SendKeyString('ABCDEFGHIJKLMNO'); will send the sting ABCDEFGHIJKLMNO the your application as if typed on the keyboard.

 

Viewing all articles
Browse latest Browse all 173

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>