我正在制作一个自定义Panel组件,该组件派生 TPanel 。
我希望我的新组件在 OnMouseEnter 和 OnMouseLeave 事件上执行一些代码,但是,我不知道如何实现它。
我看到 TPanel 已发布属性 OnMouseEnter , OnMouseLeave 。
如何覆盖这些并添加一些我自己的代码?
我的想法的例子:
TMyPanel 的默认行为,应该在组件本身中。
on event OnMouseEnter do: Color := NewColor;
on event OnMouseLeave do: Color := OldColor;
然后,我希望能够在运行时为这些事件分配一些功能。 此分配在应用程序中完成。
.. TButton1.Click ..
begin
MyPanel1.OnMouseEnter := DoSomethingMore;
MyPanel1.OnMouseLeave := DoSomethingElse;
end;
所以最后,当鼠标在新面板上时,它应该改变颜色并执行在DoSomethingMore过程中编写的其他一些操作。
由于
答案 0 :(得分:9)
Anoher方法是自己处理Windows消息:
type
TMyPanel = class(TPanel)
private
procedure CMMouseEnter(var Message: TMessage); message CM_MOUSEENTER;
procedure CMMouseLeave(var Message: TMessage); message CM_MOUSELEAVE;
published
end;
implementation
{ TMyPanel }
procedure TMyPanel.CMMouseEnter(var Message: TMessage);
begin
// Do whatever your want before the event
if Assigned(OnMouseEnter) then OnMouseEnter(Self);
end;
procedure TMyPanel.CMMouseLeave(var Message: TMessage);
begin
// Do whatever your want before the event
if Assigned(OnMouseLeave) then OnMouseLeave(Self);
end;
编辑:请参阅下文,了解更好的VCL兼容版本。
答案 1 :(得分:3)
如果它们可用,您应该覆盖DoMouseEnter和DoMouseLeave。否则,请捕获相应的消息,例如the other answer demonstrates。不要忘记调用继承,因为这将调用事件。
答案 2 :(得分:1)
这是符合VCL标准的版本(已测试D2010)
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls;
type
TMyPanel = class(TPanel)
private
procedure CMMouseEnter(var Message: TMessage); message CM_MOUSEENTER;
procedure CMMouseLeave(var Message: TMessage); message CM_MOUSELEAVE;
published
end;
TForm1 = class(TForm)
Panel1: TPanel;
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
Procedure OnMEnter(Sender: TObject);
Procedure OnMLeave(Sender: TObject);
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.FormCreate(Sender: TObject);
begin
With TMyPanel.Create(Form1) do
Begin
Parent := Form1;
Caption := 'Test';
OnMouseEnter := OnMEnter;
OnMouseLeave := OnMLeave;
End;
end;
procedure TForm1.OnMEnter(Sender: TObject);
begin
Form1.Caption := 'Entered';
end;
procedure TForm1.OnMLeave(Sender: TObject);
begin
Form1.Caption := 'Left';
end;
{ TMyPanel }
procedure TMyPanel.CMMouseEnter(var Message: TMessage);
begin
// Do whatever your want before the event
Self.Caption := 'Custom Enter';
// Call inhertied method handler
Inherited;
end;
procedure TMyPanel.CMMouseLeave(var Message: TMessage);
begin
// Do whatever your want before the event
Self.Caption := 'Custom Left';
// Call inhertied method handler
Inherited;
end;
end.