Re: How do I detect a right-click in Delphi?

Posted by John, DelphiLand Team on August 13, 2006

In Reply to How do I detect a right-click? posted by Lee Hallin P12462 on August 09, 2006

: I have a ListBox with entries. I have an OnClick event handler (which is working fine for left-clicks) but don't know how to detect that the right-button was clicked for an item in the ListBox. Is it possible to detact the right-mouse button in a ListBox?

An "OnClick" event can occur when the LEFT mouse button is pressed and released. But this event can also occur WHITHOUT a mouse click, for example when:
- an item is selected in a listbox, grid,... by pressing an arrow key;
- the spacebar is pressed while a button or check box has focus;
- and so on...

For finding out if a mouse button was pressed and which button it was, you use the OnMouseDown event:

MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer)

You can respond to the left, right, or center mouse button by looking at the parameter Button (it can be mbLeft, mbRight or mbMiddle). Here's a source code example:

procedure TForm1.ListBox1MouseDown(Sender: TObject; Button: TMouseButton;
  Shift: TShiftState; X, Y: Integer);
begin
  if Button = mbLeft then 
    ShowMessage('LEFT button')
  else if Button = mbRight then 
    ShowMessage('RIGHT button')
  else 
    ShowMessage('MIDDLE button');
end;

...or with a "case" construction:

case Button of
  mbLeft :  ShowMessage('LEFT button');
  mbRight:  ShowMessage('RIGHT button');
  mbMiddle: ShowMessage('MIDDLE button');
end;

Related Articles and Replies

Reply

Name:
Password:

Subject:

Comments:

DelphiLand Club members: enter your Membership password.
Guests can get a Forum Guest password by subscribing to the DelphiLand Newsletter.