Detecting Mouse Button Events in C#

CodeGuru content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.


This is a simple program I wrote when I needed to detect the right mouse button click in a listbox and couldn’t find it in the VS.NET IDE. In the documentation I came across a class called "MouseEventArgs".

MouseEventArgs is passed to a MouseEventHandler defined for the listbox. In the InitializeComponent() method for the form is the definition and initialization of the components of the form. I added The following to this section:


This sets the method ButtonDown to receive all mouse button events. There I determine what button was pressed, what row was clicked on, and display the results. The only events I see useful are left, right, and middle. Microsoft added two more events, XButton1 and XButton2, for it’s own devices. The documentation even has a ‘none’ event, which I cannot fathom. That’s about it.


private void
OKButtonClick(object sender, System.EventArgs e)
private void
ButtonDown(object sender, MouseEventArgs mea)
   int nDx = 0; //This will
be the 0 based index of the row clicked on

    if (mea.Button ==
MouseButtons.Right) { //Check for right button click
        m_mouse_event.Text = "Right
Button Clicked\r\n";
    else if
(mea.Button == MouseButtons.Left) { //Check for Left
button click

        m_mouse_event.Text = "Left
Button Clicked\r\n";
    nDx = mea.Y / m_listbox.ItemHeight; //Get
Index of item selected

    m_mouse_event.Text = m_mouse_event.Text +
height = " + m_listbox.ItemHeight.ToString()+ "\r\n" +
position = " + mea.X.ToString() + "\r\n" +
position = " + mea.Y.ToString() + "\n" +"\r\n"+
"Index = " + nDx.ToString();
    if ( m_listbox.Items.Count
<= nDx ) m_mouse_event.Text = m_mouse_event.Text + "\r\n" +
Clicked Beyond Table size";
//highlight row selected




Download demo project – 79 Kb

Download source – 8 Kb

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read