TButton類型不能響應鼠標雙擊事件,即使用了顯式聲明,如:
TxyButton = class(TButton)
published
property OnDBlClick;
end;
查了一下源代碼:
procedure TControl.WMLButtonDblClk(var Message: TWMLButtonDblClk);
begin
SendCancelMode(Self);
inherited;
if csCaptureMouse in ControlStyle then MouseCapture := True;
if csClickEvents in ControlStyle then DblClick; //注意這裡的csClickEvents
DoMouseDown(Message, mbLeft, [ssDouble]);
end
實際上TControl的子類默認的ControlStyle都帶有csClickEvents的:
constructor TControl.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FWindowProc := WndProc;
FControlStyle := [csCaptureMouse, csClickEvents, CSSetCaption, csDoubleClicks];
FFont := TFont.Create;
...
但是TButton類就沒那麼好運了:
constructor TButton.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
ControlStyle := [CSSetCaption, csDoubleClicks];
//注意這裡沒有csClickEvents
Width := 75;
Height := 25;
TabStop := True;
end;
解決方法有兩種:
一、攔截WM_LButtonDBLCLK
二、在TButton的聲明中顯式加入csClickEvents
constructor TxyButton.Create;
begin
inherited Create(Form1);
ControlStyle := ControlStyle + [csClickEvents];
OnDBLClick := OnDBClick;
end;
procedure TxyButton.OnDBClick(Sender: TObject);
begin
ShowMessage('DBClick');
end;