4

我正在制作一个派生TPanel的自定义 Panel 组件。

我希望我的新组件在OnMouseEnterOnMouseLeave事件上执行一些代码,但是,我不知道如何实现它。

我看到TPanel已经发布了属性OnMouseEnterOnMouseLeave

我如何覆盖这些并添加一些我自己的代码?

我的想法的例子:TMyPanel
的默认行为应该在组件本身中。

on event OnMouseEnter do: Color := NewColor;
on event OnMouseLeave do: Color := OldColor;

然后,我希望能够在运行时为这些事件分配一些功能。此分配在应用程序中完成。

.. TButton1.Click ..
begin
    MyPanel1.OnMouseEnter := DoSomethingMore;
    MyPanel1.OnMouseLeave := DoSomethingElse;
end;

所以最后,当鼠标悬停在新面板上时,它应该改变颜色并执行 DoSomethingMore 程序中编写的一些其他操作。

谢谢

4

3 回答 3

9

另一种方法是自己处理 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 兼容版本。

于 2010-02-02T08:42:16.593 回答
3

如果它们可用,您应该覆盖 DoMouseEnter 和 DoMouseLeave。否则,捕获相应的消息,就像其他答案演示的那样。不要忘记调用继承,因为这将调用事件。

于 2010-02-02T08:32:58.893 回答
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.
于 2010-02-02T15:09:56.437 回答