ASPN ActiveState Programmer Network  
ActiveState, a division of Sophos
/ Home / Perl / PHP / Python / Tcl / XSLT /
/ Safari / My ASPN /
Cookbooks | Documentation | Mailing Lists | Modules | News Feeds | Products | User Groups
Submit Recipe
My Recipes

All Recipes
All Cookbooks


View by Category

Title: using pyHook to block Windows Keys
Submitter: Brian Davis (other recipes)
Last Updated: 2008/04/08
Version no: 1.0
Category: System

 

Not Rated yet


Description:

Normally you do NOT want to block operating system key combinations but there are a few legitimate cases where you do. In my case I am making a pygame script for my 1 year old to bang on the keyboard and see/hear shapes/color/sounds in response. Brian Fischer on the pygame mailing list pointed me to pyHook. This example was taken from here: http://www.mindtrove.info/articles/pyhook.html and modified to use the pygame event system.

Source: Text Source

import pyHook
import pygame

# create a keyboard hook
def OnKeyboardEvent(event):
	print 'MessageName:',event.MessageName
	print 'Message:',event.Message
	print 'Time:',event.Time
	print 'Window:',event.Window
	print 'WindowName:',event.WindowName
	print 'Ascii:', event.Ascii, chr(event.Ascii)
	print 'Key:', event.Key
	print 'KeyID:', event.KeyID
	print 'ScanCode:', event.ScanCode
	print 'Extended:', event.Extended
	print 'Injected:', event.Injected
	print 'Alt', event.Alt
	print 'Transition', event.Transition
	print '---'
	if event.Key.lower() in ['lwin', 'tab', 'lmenu']:
		return False	# block these keys
	else:
		# return True to pass the event to other handlers
		return True

# create a hook manager
hm = pyHook.HookManager()
# watch for all keyboard events
hm.KeyDown = OnKeyboardEvent
# set the hook
hm.HookKeyboard()

# initialize pygame and start the game loop
pygame.init()

while(1):
	pygame.event.pump()

Discussion:

pyHook does not block the ctrl-alt-del combination even if you try to make it. (which is a good thing) But in my case I can now easily block the windows key and the alt-tab combination. I plan to just use the hook to block a few events and do my regular event processing after the pygame.event.pump() call, like any normal pygame loop.



Add comment

No comments.



Highest rated recipes:

1. A simple XML-RPC server

2. Web service accessible ...

3. IPy Notify

4. Changing return value ...

5. Quantum Superposition

6. Pickle objects under ...

7. Generalized delegates ...

8. Reorder a sequence (uses ...

9. Setting Win32 System ...

10. ObjectMerger




Privacy Policy | Email Opt-out | Feedback | Syndication
© 2006 ActiveState Software Inc. All rights reserved.