随笔 - 2146  文章 - 97 评论 - 11767 trackbacks - 253


问题来源: http://www.cnblogs.com/del/archive/2009/10/09/1579614.html#1779614

这几天家有病人, 几天没上网了; 看到这个问题我会, 顺便回复了.

发送代码:
unit Unit1;

interface

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

type
  TForm1 = class(TForm)
    Button1: TButton;
    Edit1: TEdit;
    procedure Button1Click(Sender: TObject);
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.Button1Click(Sender: TObject);
var
  h: HWND;
  Size: Integer;
  CopyDataStruct: TCopyDataStruct;
begin
  h := FindWindow(nil, '接收窗口'); { 按标题查找目标窗口 }
  if h > 0 then
  begin
    Size := ByteLength(Edit1.Text) + 2;   { 多出的两个字节用于后面的 #0 }
    CopyDataStruct.lpData := PChar(Edit1.Text + #0); { 要发送的字符串, #0 表示 PChar 结束}
    CopyDataStruct.dwData := WM_COPYDATA;            { 指定消息类型 }
    CopyDataStruct.cbData := Size;                   { 指定要发送的数据的大小 }
    SendMessage(h, WM_COPYDATA, 0, Integer(@CopyDataStruct)); { 发送 }
  end;
end;

end.


接收代码:
unit Unit1;

interface

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

type
  TForm1 = class(TForm)
    Memo1: TMemo;
    procedure FormCreate(Sender: TObject);
  private
  protected
    procedure WMCopyData(var Message: TWMCopyData); message WM_COPYDATA;
  public
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.FormCreate(Sender: TObject);
begin
  Caption := '接收窗口';
end;

procedure TForm1.WMCopyData(var Message: TWMCopyData);
begin
  Memo1.Lines.Add(PChar(Message.CopyDataStruct.lpData));
end;

end.


该代码已在 Delphi 2010 下测试过了.

发现 skymesh 朋友对消息操作不是太熟, 顺便告知个小技巧(其实博客中可能早提到过):
在 TForm1 = class(TForm) ... end; 中执行 Ctrl+空格;
然后输入: wm...(譬如本例输入 wmcopyd 即可) 后回车;
接着执行 Ctrl+Shift+C, 会自动完成上面大部分的消息代码.

posted on 2010-03-15 18:24  万一  阅读(...)  评论(...编辑  收藏