xRuhRohx
xRuhRohx

Reputation: 422

How can I get mouse location on a button?

VB.NET Visual Studio

I have several buttons that I add at runtime, and I have a MouseDown event handler for the click event. Left click works just fine, but the right click event fires, but doesn't do what I need it to.

If e.Button = Windows.Forms.MouseButtons.Right Then
    If sender.Bounds.Contains(e.Location) = True Then
        ContextMenuStrip.Show(Cursor.Position)
    End If
End If

I shortened this to make it easier to read.

When I look at e.Location, it shows the mouse location in relation to the button. So if my button is at 400, 600, the location of the mouse should be in that area, but the mouse location comes back with 20, 30 because it is at 20,30 inside the button.

How can I do this right click event properly?

Upvotes: 1

Views: 1485

Answers (1)

Reza Aghaei
Reza Aghaei

Reputation: 125187

MouseDown event raises when the mouse is down on your control, so the mouse is surely in your control bounds and you don't need to check if the button contains e.Location.

To show the context menu strip, if you assign the context menu strip to ContextMenuStrip property of your control, then you don't need to do anything and the menu will show automatically. But if for any reason you want to handle MouseDown event, you can use either of these options:

  • ContextMenuStrip1.Show(DirectCast(sender, Control), e.Location)

  • ContextMenuStrip1.Show(MousePosition)

Note: Just for learning purpose if you want to check if e.Location is in your button, you can use either of these options:

  • Button1.ClientRectangle.Contains(e.Location)
  • Button1.Bounds.Contains(Button1.Parent.PointToClient(Button1.PointToScreen(e.Location)))

Or some other combinations using PointToClient, PointToScreen, RectangleToClient, RectangleToScreen methods of controls.

Upvotes: 1

Related Questions