Search code examples
c#winformsevent-handling

Right clicking a button doesn't trigger an event


public void click(object? sender, MouseEventArgs e)
{
    var btn = sender as MyButton;
    
    if (e.Button == MouseButtons.Right)
    {
        btn.ForeColor = Color.Green;
        btn.Text = "FLAG";
    }
    else
    {
       // code that is here works so it doesn't matter
    }
}

So, when I left-click a button that is hooked to that function, it either shows a number on that button or "BOMB" text. This part works as supposed to. But when I right-click, I want the button to have green text "FLAG". As you have guessed, it doesn't work. Absolutely nothing happens.

I don't even know what to try, everyone says that you should use

(if e.Button == MouseButtons.Right)

but doing this changed nothing.

I searched a lot, but nobody seemed to have that same problem.


Solution

  • The MS documentation for the Control.Click event shows a table of events raised for actions such as Left Mouse Click and Right Mouse Click.

    abridged chart


    Based on this information, you might want to try the MouseDown event instead to achieve your objective. (As shown here, the BeginInvoke is to avoid blocking in the MouseDown handler which ensures that the MouseUp event will not be interfered with in any way.)

        public MainForm()
        {
            InitializeComponent();
            button.Click += (sender, e) =>
            { 
                // According to documentation, will 'not' be fired for Right button
            };
    
            button.MouseDown += (sender, e) =>
            { 
                if(sender is Button btn)
                {
                    switch (e.Button)
                    {
                        case MouseButtons.Right:
                            BeginInvoke((() =>
                            {
                                // Do something
                            }));
                            break;
                    }
                }
            };
        }