通过消息跨进程发送与接收 TCopyDataStruct 数
该代码已在 Delphi 2010 下测试过了.
- 发送代码: --------------------------------------------------------------------------------
- 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.
发现 skymesh 朋友对消息操作不是太熟, 顺便告知个小技巧(其实博客中可能早提到过):
在 TForm1 = class(TForm) ... end; 中执行 Ctrl+空格;
然后输入: wm...(譬如本例输入 wmcopyd 即可) 后回车;
接着执行 Ctrl+Shift+C, 会自动完成上面大部分的消息代码.
顶(0)
踩(0)
- 最新评论