网上有很多的关于模拟按键的例子,经过实验,我选如下一组函数
procedure SendShift(H: HWnd; Down: Boolean); var vKey, ScanCode: Word; lParam: longint; begin vKey:= $10; ScanCode:= MapVirtualKey(vKey, 0); lParam:= longint(ScanCode) shl 16 or 1; if not(Down) then lParam:= lParam or $C0000000; SendMessage(H,WM_KEYDOWN, vKey, lParam); end;
procedure SendCtrl(H: HWnd; Down: Boolean); var vKey, ScanCode: Word; //wParam lParam: longint; begin vKey:= $11; ScanCode:= MapVirtualKey(vKey, 0);{虚拟键转换为扫描码} lParam:= longint(ScanCode) shl 16 or 1; if not(Down) then lParam:= lParam or $C0000000; SendMessage(H,WM_KEYDOWN, vKey, lParam); end;
procedure SendKey(H: Hwnd; Key: char); var vKey, ScanCode, wParam: Word; lParam, ConvKey: longint; Shift, Ctrl: boolean; begin ConvKey:= OemKeyScan(ord(Key)); Shift:= (ConvKey and $00020000) <> 0; Ctrl:= (ConvKey and $00040000) <> 0; ScanCode:= ConvKey and $000000FF or $FF00; vKey:= ord(Key); wParam:= vKey; lParam:= longint(ScanCode) shl 16 or 1; if Shift then SendShift(H, true); if Ctrl then SendCtrl(H, true); SendMessage(H, WM_KEYDOWN, vKey, lParam); SendMessage(H, WM_CHAR, vKey, lParam); lParam:= lParam or $C0000000; SendMessage(H, WM_KEYUP, vKey, lParam); if Shift then SendShift(H, false); if Ctrl then SendCtrl(H, false); end;
//--模拟键盘输入 procedure SendText(h:THandle; str:string); var n:integer; begin n:=1; while n<>length(str)+1 do begin if ord(str[n])<130 then begin SendMessage(h, $0286,ord(str[n]),0); n:=n+1; end else begin SendMessage(h, $0286,(ord(Str[n]) shl 8)+ord(Str[n+1]),0); n:=n+2; end; end; end;
|
请发表评论