Delphi 将消息从帧发送到主窗体
我有一份VCL表格申请表,由三个单元组成。单元1定义了表单,并包括单元2中定义的具有多个Tlabel组件的框架的多个实例。第3单元声明了可在整个程序中使用的各种共享常量和变量 当用户单击其中一个框架时,它会为单元2中的变量设置某些值,并且必须通知表单采取影响表单上其他单元格和组件的操作。由于在第3单元的uses子句中包含第1单元将创建循环引用,因此我认为向表单发送消息将是执行所需操作的最佳选择 在我的第一次尝试中,我设置如下:Delphi 将消息从帧发送到主窗体,delphi,message,Delphi,Message,我有一份VCL表格申请表,由三个单元组成。单元1定义了表单,并包括单元2中定义的具有多个Tlabel组件的框架的多个实例。第3单元声明了可在整个程序中使用的各种共享常量和变量 当用户单击其中一个框架时,它会为单元2中的变量设置某些值,并且必须通知表单采取影响表单上其他单元格和组件的操作。由于在第3单元的uses子句中包含第1单元将创建循环引用,因此我认为向表单发送消息将是执行所需操作的最佳选择 在我的第一次尝试中,我设置如下: Unit 1 Interface Uses ..., Winapi.
Unit 1
Interface
Uses ..., Winapi.Messages, Unit2, Unit3;
Type
Form1 = Class(TForm);
//List of frames and components
...
private
...
{ Private declarations }
procedure OnDisplayMessage(var Msg: TMessage); message WM_MY_MESSAGE;
...
End;
Implementation
...
procedure TForm1.OnDisplayMessage(var Msg: TMessage);
begin
TakeAction (inputlist);
end;
Unit 2 //Common program constants and variables
Interface
const
WM_MY_MESSAGE = WM_USER + 100;
...
Unit 3 //Frame component definition
interface
Uses ...Winapi.Messages, Unit2;
Types
TCellFrame = class(TFrame)
Item1: TLabel;
Item2: TLabel;
Item3: TLabel;
Item4: TLabel;
Item5: TLabel;
Item6: TLabel;
Item7: TLabel;
Item8: TLabel;
Item9: TLabel;
procedure FrameClick(Sender: TObject);
Implementation
procedure TCellFrame.FrameClick(Sender: TObject);
begin
...
SendMessage(HWND_BROADCAST,WM_MY_MESSAGE,0,0);
...
end;
虽然代码已编译,但未执行所需的操作。我假设消息没有传递到表单,因此我尝试用Windows方法AppHookFunction()
替换OnDisplayMessage()
,如下所示:
第一单元
此选项似乎也无法发送消息。基本操作在测试时运行良好,因此我相当确定失败在于传递消息。我是否对消息从帧传递到表单的方式有误解,或者是否有其他方法可以在由frame onclick事件生成的表单中实现操作?是的,有些误解,有些困惑,可能是复制粘贴错误。。。在第一段代码中,您正在收听WM_DISPLAY_CLEARLIST,但正在发送WM_MY_消息。在第二个代码片段中,不清楚AppHookFunc为什么会处理任何消息。首先,您不需要广播,表单和框架之间有一种父子关系。您可以通过GetParentForm从框架中获取表单。其次,我认为这不需要消息传递,但您可以通过从实现部分以另一种方式引用来绕过循环引用。我想你最好使用某种回调。表单可以将方法地址设置为帧属性,以便在需要时回调帧。您还需要更正单位。在第一段中,你说unit2是框架和标签,unit3是常量等等。。在代码段中,unit2是常量,unit3是框架、标签。事实上,一般来说,不要为问题提取代码。准备一个,你就不会有这些问题,我们也不会有这些问题。在unit2(3?)的实现部分中,使用unit1。然后在任何方法中都可以访问父窗体(TForm1(GetParentForm(Self,True))。
Interface
Uses ..., Winapi.Messages, Unit2, Unit3;
Type
Form1 = Class(Tform;)
//List of frames and components
...
private
...
{ Private declarations }
function AppHookFunc(var Message : TMessage) : Boolean;
...
End;
Implementation
...
function TForm1.AppHookFunc(var Message : TMessage) : Boolean;
begin
Result := False;
if Message.Msg = WM_MY_MESSAGE then begin
TakeAction (inputlist);
Result := True;
end;
end;
Unit 2 //Common program constants and variables
Interface
const
WM_MY_MESSAGE = WM_USER + 100;
...
Unit 3 //Frame component definition
interface
Uses ...Winapi.Messages, Unit2;
Types
TCellFrame = class(TFrame)
Item1: TLabel;
Item2: TLabel;
Item3: TLabel;
Item4: TLabel;
Item5: TLabel;
Item6: TLabel;
Item7: TLabel;
Item8: TLabel;
Item9: TLabel;
procedure FrameClick(Sender: TObject);
Implementation
procedure TCellFrame.FrameClick(Sender: TObject);
begin
...
SendMessage(HWND_BROADCAST,WM_MY_MESSAGE,0,0);
...
end;