用Delphi读取鼠标所在位置单词

有些字典程序具有这样的功能──当我们用鼠标点取某个英文单词后,程序就显示该单词的中文意思,这样的程序怎样编写呢?首先我们要将中英文对照字典事先建立好,然后在程序中获取使用者点取的单词,接着在中英文对照字典查找所选的单词,最后将翻译结果显示出来。本文就着力说明如何在程序中读取鼠标所在位置的单词。
   程序的关键在于需要向文本框传递消息EN_CHARFROMPOS。该消息用于读取当前鼠标位于文本框的第几行第几列上。在发送该消息时,参数wParam没有作用;参数lParam为长整型,用于指定鼠标的坐标位置,其中两个高字节指定Y,两个低字节指定X。返回值为长整型,其中两个高字节指定鼠标位于第几个字符上,两个低字节指定鼠标位于第几个列上。
   程序代码如下:
   unit Unit1;

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

type
   TForm1 = class(TForm)
   Memo1:TMemo;

procedure Memo1MouseDown(Sender:TObject;Button:TMouseButton;

Shift:TShiftState;X,Y:Integer);

procedure FormCreate(Sender:TOb—ject);

private
   {Private declarations}

public
   Function IsSeparetor(ch:Char):Boolean;

Function GetWord(pos:Word):String;

{Public declarations}

end;

var
   Form1:TForm1;

implementation
   {$R*.DFM}

{函数IsSparetor用于判定一个字符是否为分隔符}
   Function TForm1.IsSeparetor(ch:Char):Boolean;
   begin
   IsSeparetor:= False;

If ch in[' ',', '.','?',#10,#13]then
   IsSeparetor:= True
   End;

{函数GetWord用于读取鼠标所在位置的单词}

Function TForm1.GetWord(pos:Word):String;

var
   st:string;pos1,pos2:Word;

i:Longint;w:string;

begin
   w:='':pos1:= 1;getword:='';

{读取文本框中的内容及文本长度}
   st:=Memo1.Lines.Text ;

pos2:= length(st)

{向前搜寻当前单词的起始位置}

For i:= pos - 1 downTo 1 do
   If IsSeparetor(st[i])Then
   begin
   pos1:= i + 1;break
   end;

{向后搜寻当前单词的结束位置}

For i:= pos To pos2 do
   If IsSeparetor(st[i])Then
   begin
   pos2:= i - 1; break
   end;
   {截取pos1-pos2间的字符,以构成一个单词}
   if pos1<=pos2 then
   begin
   For i:= pos1 To pos2 do
   w:=w+st[i];

GetWord:= '单词:'+w
   end
   End;

procedure TForm1.Memo1MouseDown(Sender:TObject;Button:TMouseButton;

Shift:TShiftState;X,Y:Integer);

var
   lc:Longint;CharPos:Word;

begin
   {向文本框传递消息EN_CHARFROMPOS}
   lc:= SendMessage(Memo1.handle,EM_CHARFROMPOS,0,x+(y shl 16)); {取得鼠标位于第几个字符上}

CharPos:=Word(lc)
   {显示我们所点取的单词}

Memo1.Hint:= GetWord(CharPos)
   end;

procedure TForm1.FormCreate(Sender.TObject);

begin
   Memo1.ShowHint:=True
   end;
   end.
   以上代码在Windows 98、Delphi 5.0环境下调试通过。