delphi 如何使用SendMessage发送后台组合键消息(Ctrl+XXX)

2018-10-31

unit Unit1;

interface

uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls;

type
TForm1 = class(TForm)
procedure FormKeyPress(Sender: TObject; var Key: Char);
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;

var
Form1: TForm1;
MyHandle : hWnd;

implementation

{$R *.DFM}

procedure SendCtrl(H: HWnd; Down: Boolean);
var
vKey, ScanCode : Word;
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 : Word;
lParam, ConvKey: longint;
Ctrl: boolean;
begin
ConvKey:= OemKeyScan(ord(Key));
Ctrl:= (ConvKey and $00040000) <> 0;
ScanCode:= ConvKey and $000000FF or $FF00;
vKey:= ord(Key);
lParam:= longint(ScanCode) shl 16 or 1;
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 Ctrl then SendCtrl(H, false);
end;

procedure TForm1.FormKeyPress(Sender: TObject; var Key: Char);
begin
if MyHandle <> 0 then SendKey(MyHandle, Key);
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
MyHandle := FindWindowEx(FindWindow('NotePad', nil), 0, 'Edit', nil);
end;

end.
运行后在窗体随便按键你会发现记事本里就是你所按键的内容!
可根据自行需要自己修改代码,这里就不列出了

阅读119