Detecting whether a mouse button is down in vb.net

4.3k views Asked by At

I don't want to use the mouseup event because I want to allow the user to drag outside the control. I need to check the state via a timer. I vaguely remember doing this before at some point by using

If MouseButtons = MouseButtons.Left Then...

But now it says that MouseButtons is a type and cannot be used as an expression (which is true, its an enum type).

Maybe they changed things or maybe I just remember wrong.. either way, how would I check if the button is still down?

3

There are 3 answers

0
Trevor On BEST ANSWER

This is tried and tested. I created a new class: testmouseclass and created a shared function you can use anytime to determine if the LeftMouseButton is down. This is possible with the help of GetAsyncKeyState call.

 Imports System.Runtime.InteropServices 'Need to import...

 Public Class testmouseclass

 <DllImport("user32.dll", CharSet:=CharSet.Auto, ExactSpelling:=True)> Public Shared Function GetAsyncKeyState(ByVal vkey As Long) As Long
End Function

Public Shared Function LeftMouseIsDown() As Boolean
    Return GetAsyncKeyState(Keys.LButton) > 0 And &H8000
End Function

 End Class

Example Usage

   Private Sub Timer1_Tick(sender As Object, e As System.EventArgs) Handles Timer1.Tick
    If testmouseclass.LeftMouseIsDown() Then MsgBox("It IS!")
   End Sub 

Depending on the timer tick's this can be a headache as well. Not sure how you are using this, but in my example I had the timer at 3 seconds and when I held the LeftMouseButton down a message popped up and when I clicked it again it popped up again because of the timer and the left mouse was down. Also this work's even outside of your application...

6
Justin Ryan On

What you want is to test the Mouse.LeftButton property.

1
Theo Jacobs On
If System.Windows.Input.Mouse.LeftButton = Windows.Input.MouseButtonState.Pressed Then