如何覆盖父类的事件(100分)

  • 主题发起人 主题发起人 cocobom
  • 开始时间 开始时间
C

cocobom

Unregistered / Unconfirmed
GUEST, unregistred user!
学控件开发过程中,想做一个EDIT,当焦点进入时变黄色,离开时恢复。
如何修改TEdit的Enter事件? 具体的代码是怎样的?
 
参考:
http://www.delphibbs.com/delphibbs/dispq.asp?lid=1749085
 
继承TEdit,override这两个方法
procedure DoEnter; dynamic;
procedure DoExit; dynamic;
 
添加了一个属性,可以在设计阶段,选择当Edit获得焦点的时候的颜色值!

unit EditEx;

interface

uses
SysUtils, Classes, Controls, StdCtrls, Graphics;

type
TEditEx = class(TEdit)
private
{ Private declarations }
FUnFocusColor: TColor;
FFocusColor: TColor;
procedure SetFocusColor(const Value: TColor);
protected
{ Protected declarations }
procedure DoEnter; override;
procedure DoExit; override;
public
{ Public declarations }
published
{ Published declarations }
property FocusColor : TColor read FFocusColor write SetFocusColor;
end;

procedure Register;

implementation

procedure Register;
begin
RegisterComponents('Samples', [TEditEx]);
end;

{ TEditEx }

procedure TEditEx.DoEnter;
begin
FUnFocusColor := Font.Color;
Font.Color := FFocusColor;
Refresh;
inherited;
end;

procedure TEditEx.DoExit;
begin
Font.Color := FUnFocusColor;
Refresh;
inherited;
end;


procedure TEditEx.SetFocusColor(const Value: TColor);
begin
if FFocusColor = Value then Exit;
FFocusColor := Value;
if Focused then
begin
Font.Color := FFocusColor;
Refresh;
end;
end;

end.
 
unit MyEdit;

interface

uses
SysUtils, Classes, Controls, StdCtrls,Graphics;

type
TMyEdit = class(TEdit)
private
{ Private declarations }
FFontColor:TColor;
//继承并修改TCustomEdit和TWinControl中的两个事件
procedure CMEnter(var Message: TCMEnter); message CM_ENTER;
procedure CMExit(var Message: TCMExit); message CM_EXIT;
protected
{ Protected declarations }
public
{ Public declarations }
constructor Create(AOwner: TComponent); override;
published
{ Published declarations }
end;

procedure Register;
implementation
procedure Register;
begin
RegisterComponents('Samples', [TMyEdit]);
end;
{ TMyEdit }
procedure TMyEdit.CMEnter(var Message: TCMEnter);
begin
inherited;
//Enter时,把color改为黄色
Color:=clYellow;
end;

procedure TMyEdit.CMExit(var Message: TCMExit);
begin
inherited;
Color:=FFontColor; //还原Color
end;

constructor TMyEdit.Create(AOwner: TComponent);
begin
inherited;
FFontColor:=Color; //记录原来的color
end;

end.
-------------------------------------
demo如下:
unit U_YellowEdit;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs,MyEdit, StdCtrls;

type
TForm1 = class(TForm)
Button1: TButton;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;

var
Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.Button1Click(Sender: TObject);
begin
//这样做只是为了省去安装、卸载package(Component)的麻烦
//等测试OK,再装也不迟
with TMyEdit.Create(self) do
begin
Parent:=Self;
left:=Random(ClientWidth);
Top:=Random(ClientHeight);
Enabled:=True;
visible:=True;
end;
end;

end.
 
后退
顶部