Search code examples
c#winforms

In Visual Studio 2022, C#, Handling MouseDown Event


In Visual Studio 2022, C#, with a simple code like below, if you press Right Mouse Button WINFORM closes simply, but Mouse event is still active and triggers Windows Desktop Right Mouse Event and shows related shortcut menu:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        MouseDown += Form1_MouseDown;
    }
    private void Form1_MouseDown(object? sender, MouseEventArgs e)
    {
        Close();
    }
}

Is there a way to prevent this, not showing shortcut menu of windows?


Solution

  • You're using the wrong event.
    In Winforms, When a mouse button is clicked you get the following events, in this order:

    1. MouseDown
    2. Click
    3. MouseClick
    4. MouseUp

    The MouseDown event is the first that fires, but it's not the only one. Since you're closing your form in the mouse down, the next events gets handled by the operating system, so you get the context menu as a result of the MouseUp event when you click the right button.

    If you want to handle it properly, you can use either the MouseClick or the MouseUp event.

    For more information, read the documentation.