How do I detect a right-click in Delphi?


How do I detect a right-click?

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 detect the right-mouse button in a ListBox?


An "OnClick" event can occur when a 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);
  if Button = mbLeft then 
    ShowMessage('LEFT button')
  else if Button = mbRight then 
    ShowMessage('RIGHT button')
    ShowMessage('MIDDLE button');

...or with a "case" construction instead of if then / else / else:

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