Useful to know – to select items in a ListBox with a right mouse click wire up the following code to the MouseDown event:
private void LB_MouseDown(object sender, MouseEventArgs e)
{
// Select item if right click.
if (MouseButtons.Right == e.Button)
{
Point pt = new Point(e.X, e.Y);
LB.SelectedIndex = LB.IndexFromPoint(pt);
}
}
Advertisement

Sweet–thanks for posting the example.
Rob,
I prefer this version it allows you to wire it to multiple listboxes.
private void listBox_MouseDown(object sender, MouseEventArgs e)
{
ListBox lst = (ListBox) sender;
// Select item if right click.
if (MouseButtons.Right == e.Button)
{
Point pt = new Point(e.X, e.Y);
lst.SelectedIndex = lst.IndexFromPoint(pt);
}
}
Generally I prefer the “SenderType foo = (SenderType) sender;” pattern as opposed to calling the item by its class member name in events.
Guess there are plenty of ways of doing this, easiest way i found was to send a left click before the right mouse button comes back up!
Private Declare Function SetCursorPos Lib “user32″ (ByVal x As Long, ByVal Y As Long) As Long
Private Declare Sub mouse_event Lib “user32″ (ByVal dwFlags As Long, ByVal dx As Long, ByVal dy As Long, ByVal cButtons As Long, ByVal dwExtraInfo As Long)
Private Const MOUSEEVENTF_LEFTDOWN = &H2
Private Const MOUSEEVENTF_LEFTUP = &H4
Private Sub ListBox1_MouseDown(ByVal Button As Integer, ByVal Shift As Integer, ByVal x As Single, ByVal Y As Single)
If Button = 2 Then
mouse_event MOUSEEVENTF_LEFTDOWN, 0&, 0&, 0&, 0&
mouse_event MOUSEEVENTF_LEFTUP, 0&, 0&, 0&, 0&
End If
End Sub
Like that! =]