源程序如下:
unit sendkey1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs,sndkey32, StdCtrls; //注意該行要添加sndker32!!
type
TForm1 = class(TForm)
Edit1: TEdit;
Edit2: TEdit;
Button1: TButton;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.Button1Click(Sender: TObject);
begin
Edit2.SetFocus; //將焦點置於Edit2
SendKeys(Pchar(Edit1.Text),False); //將Edit1中的字符串發送給Edit2
//事先需進行轉換
end;
end.
很簡單,是不是?其實不僅Edit控件,像Memo、RichEdit等空件均可接收發送的字符。
上面的例子只是在本應用程序內傳遞字符串,
下面的例子是將字符串發送給Microsoft Word。其所用控件與上例相差不大。
源程序為:
unit unit1;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs
,sndkey32, StdCtrls; //不要忘了sndKey32!
type
TForm1 = class(TForm)
Button1: TButton;
Edit1: TEdit;
Button2: TButton;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.DFM}
{ 該函數將焦點置於Word,若失敗,返回False}
function SetFocusToWord:boolean;
var
f:boolean;
begin
f:=true;
if not AppActivate('文檔 1 - Microsoft Word') then
{
字符串內容為:文檔空格1空格-空格Microsoft空格Word
}
begin
f:=False;
MessageDlg('沒找到Word!',mtError,[mbOk],0); //顯示錯誤
exit;
end;
result:=f;
end;
procedure SetForMactive; //該子程序將焦點置回
begin
Appactivate('SendToWord');
form1.SetFocus;
form1.Edit1.SetFocus;
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
if not SetFocusToWord then exit; //沒找到Word,退出
sendkeys(Pchar(form1.edit1.text),false); //找到了,發送字符串
SetForMactive;
end;
procedure TForm1.Button2Click(Sender: TObject);
begin
if not SetFocusToWord then exit; //沒找到Word,退出
sendkeys('%{F4}',false); //發送Alt+F4,關閉Word
SetForMactive;
end;
end.
該例子只是簡單演示一下,實際上大家可以改動激活word的部分(本文查找'文檔 1 - Microsoft Word'來實現,
顯得有些太簡單了。)
Delphi本身也帶有與Office協作的一系列控件,但只進行簡單的協作,這樣不是更簡單麼?
SendKeys函數的功能很強大,不然Borland也不會在安裝盤中提供這個文件。更好的利
SendKeys的設想,就要看各位朋友的了!