Emulate a Click Event for Right-Clicks Over Commandbutton Controls

Emulate a Click Event for Right-Clicks Over Commandbutton Controls

Sometimes it’s useful to trap the right click over controls such as CommandButton. Unfortunately, the Click event only fires for left button clicks. The MouseDown and MouseUp events fire for both buttons, and even report which button was clicked, but nothing in life could ever be that simple, right?

The first problem is that if you use the MouseDown event, you trap the click when the user clicks down on the key, which is counter to the way things normally work in Windows. For instance, when you click the left button, the control’s Click event won’t fire until you release, giving you the ability to slide off the control before releasing. A fire-on-downstroke event gives no such safety net.

So you’re probably thinking, “Well, then just use the MouseUp event!” This solution creates another gotcha: Even if you slide off the control before releasing, the MouseUp event fires anyway!

Fortunately, the MouseUp event reports the mouse cursor’s X and Y positions, and using simple math comparing them to the control’s placement and size, it’s easy to determine whether the mouse was over the control at the instant it was released. Here’s how you do it:

 Option ExplicitPrivate Sub Command1_MouseUp(Button As Integer, _	Shift As Integer, X As Single, Y As Single)Dim OffMe As Boolean		If Button = 2 Then	'right button			X = X + Command1.Left			Y = Y + Command1.Top			OffMe = False			Select Case X				Case Is < Command1.Left, Is > _				(Command1.Left + Command1.Width)					OffMe = True		End Select		Select Case Y			Case Is < Command1.Top, Is > _				(Command1.Top + Command1.Height)					OffMe = True		End Select		If Not OffMe Then			'*****************			'Your code goes here			'*****************		End If	End IfEnd Sub
See also  What Are International Payments, And How Do They Work?

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist