Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to 'close on external click' for a TPanel (like TCombo) in Delphi

Tags:

delphi

vcl

I want to mimic the TComBo list function which is closed when the user click 'outside' the list, but for another component (a TPanel). In Delphi XE2. Any Idea ?

like image 577
philnext Avatar asked Dec 27 '22 17:12

philnext


1 Answers

Assuming your panel is focussed (as I "read" from your question), then respond to the CM_CANCELMODE message which is send to all focussed windows.

type
  TPanel = class(Vcl.ExtCtrls.TPanel)
  private
    procedure CMCancelMode(var Message: TCMCancelMode); message CM_CANCELMODE;
  end;

  ...

{ TPanel }

procedure TPanel.CMCancelMode(var Message: TCMCancelMode);
begin
  inherited;
  if Message.Sender <> Self then
    Hide;
end;

When the panel itself is not focussed, e.g. a child control is, then this will not work. In that case you could track all mouse clicks (e.g. by the use of a TApplicationEvents.OnMessage handler) and compute whether the click was within the bounds of your panel:

procedure TForm1.ApplicationEvents1Message(var Msg: tagMSG;
  var Handled: Boolean);
begin
  if Panel1.Visible and
      (Msg.message >= WM_LBUTTONDOWN) and (Msg.message <= WM_MBUTTONDBLCLK) and
      not PtInRect(Panel1.ClientRect, Panel1.ScreenToClient(Msg.pt)) then
    Panel1.Hide;
end;

But this still will not succeed when the click was - for example - in the list of a combobox which belongs to the panel but is partly unfolded outside of it. I would not know how to distil the panel from that click information.

like image 153
NGLN Avatar answered Mar 01 '23 23:03

NGLN