Global Hotkeys

Share your advanced PureBasic knowledge/code with the community.
User avatar
Rescator
Addict
Addict
Posts: 1769
Joined: Sat Feb 19, 2005 5:05 pm
Location: Norway

Global Hotkeys

Post by Rescator »

Code updated For 5.20+

Code: Select all

#VK_MEDIA_PLAY_PAUSE=$B3

Structure _GlobalHotkeys
 window.l
 event.l
EndStructure
Global NewList GlobalHotkeys._GlobalHotkeys()

Procedure AddGlobalHotkey(window,event,modifiers,vk)
Define.l result
 result=RegisterHotKey_(WindowID(window),event,modifiers,vk)
 If result
  LastElement(GlobalHotkeys())
  AddElement(GlobalHotkeys())
  GlobalHotkeys()\window=window
  GlobalHotkeys()\event=#VK_MEDIA_PLAY_PAUSE
 EndIf
 ProcedureReturn result
EndProcedure

Procedure RemoveGlobalHotkey(window,event)
Define.l result
 ForEach GlobalHotkeys()
  If (GlobalHotkeys()\window=window) And (GlobalHotkeys()\event=event) : Break :  EndIf
  ProcedureReturn #False
 Next
 result=UnregisterHotKey_(WindowID(window),event)
 If result
  DeleteElement(GlobalHotkeys(),1)
 EndIf
 ProcedureReturn result
EndProcedure

Procedure RemoveAllGlobalHotkeys()
 ForEach GlobalHotkeys()
  UnregisterHotKey_(WindowID(GlobalHotkeys()\window),GlobalHotkeys()\event)
  DeleteElement(GlobalHotkeys(),0)
 Next
EndProcedure

Procedure WindowCallback(hwnd,msg,wparam,lparam)
 result=#PB_ProcessPureBasicEvents
 Select msg 
  Case #WM_HOTKEY
   If wparam=#VK_MEDIA_PLAY_PAUSE
    Debug "#VK_MEDIA_PLAY_PAUSE pressed"
    result=#False
   EndIf
 EndSelect
 ProcedureReturn result
EndProcedure 

#Window=1

If OpenWindow(#Window,300,250,400,200,"test",#PB_Window_SystemMenu)
 
 If AddGlobalHotkey(#Window,#VK_MEDIA_PLAY_PAUSE,0,#VK_MEDIA_PLAY_PAUSE)=#False
  Debug "failed to register hotkey"
 EndIf
 SetWindowCallback(@WindowCallback(),1)
 
 Repeat
  event=WaitWindowEvent()
 Until event=#PB_Event_CloseWindow
EndIf 

RemoveAllGlobalHotkeys()