Page 1 of 1

Get mouse button state without ExamineMouse()

Posted: Sat Oct 25, 2014 4:34 pm
by BasicallyPure
This trick uses the win API command GetAsyncKeyState_
so this is for those who are not familiar with it.

Here it is wrapped in a handy procedure and it works with right
or left hand mouse configuration.
Use the built in #PB_MouseButton_... constants to choose which
button you wish to examine.

You can use this in your code anytime you want to check the state
of left, middle, or right mouse buttons.

This is for windows only.

BP

Code: Select all

; by BasicallyPure 10/14/2014
; PureBasic 5.30
; OS = Windows only
; forum topic: http://www.purebasic.fr/english/viewtopic.php?f=12&t=60831

EnableExplicit

Procedure GetMouseButtonState(button.i)
   ; checks if a mouse button is pressed
   ; ExamineMouse() is not required
   ; works for left or right hand mouse configuration
   ; button parameter should be:
   ;    #PB_MouseButton_Left  or
   ;    #PB_MouseButton_Right or
   ;    #PB_MouseButton_Middle
   ;
   ; procedure returns #True if button is pressed
   
   Protected result = #False
   
   Static firstRun   = #True
   Static _VK_LBUTTON = #VK_LBUTTON
   Static _VK_RBUTTON = #VK_RBUTTON
   
   If firstRun = #True
      firstRun = #False
      If GetSystemMetrics_(#SM_SWAPBUTTON)
         Swap _VK_LBUTTON, _VK_RBUTTON
      EndIf
   EndIf
   
   Select button
      Case #PB_MouseButton_Left   : result = GetAsyncKeyState_(_VK_LBUTTON) >> 15 & 1
      Case #PB_MouseButton_Middle : result = GetAsyncKeyState_(#VK_MBUTTON) >> 15 & 1
      Case #PB_MouseButton_Right  : result = GetAsyncKeyState_(_VK_RBUTTON) >> 15 & 1
   EndSelect
   
   ProcedureReturn result
EndProcedure


; example

Define combo, state, Quit = #False

If OpenWindow(0, 0, 0, 300, 150, "press 'space' to test", #PB_Window_ScreenCentered | #PB_Window_SystemMenu)
   
   combo = ComboBoxGadget(#PB_Any, 10, 10, 100, 25)
   AddGadgetItem(combo, 0, "left button")
   AddGadgetItem(combo, 1, "middle button")
   AddGadgetItem(combo, 2, "right button")
   SetGadgetState(combo,0)
   
   AddKeyboardShortcut(0, #PB_Shortcut_Space, 1)
      
   Repeat
      Select WaitWindowEvent()
         Case #PB_Event_CloseWindow
            Quit = #True
         Case #PB_Event_Menu
            If EventMenu() = 1
               Select GetGadgetState(combo)
                  Case 0 : state = GetMouseButtonState(#PB_MouseButton_Left)
                  Case 1 : state = GetMouseButtonState(#PB_MouseButton_Middle)
                  Case 2 : state = GetMouseButtonState(#PB_MouseButton_Right)
               EndSelect
               
               Debug "button state is " + state
            EndIf
      EndSelect
   Until Quit = #True
   
EndIf