I l@ve RuBoard Previous Section Next Section

7.17 Displaying Decoded Hotkeys for Shortcuts in Windows

Credit: Bill Bell

7.17.1 Problem

You need to display the hotkeys associated with Windows shortcuts as readable key-combination names, such as Alt-Ctrl-Z or Shift-Ctrl-B.

7.17.2 Solution

Key combinations are returned as binary-coded numbers, but it's not hard to decode them into human-readable combinations:

import sys
# Append to sys.path the complete path to the folder that contains 
# 'link.py' (the demo use of pythoncom.CoCreateInstance with
# shell.CLSID_ShellLink in the ActiveState distribution of Python)
# so that link can be imported as a module
import link
import commctrl
class PyShortcut_II(link.PyShortcut):
    def decode_hotkey(self):
        hk = self.GetHotkey(  )
        result = ''
        if hk:
             mod = hk >> 8
             if mod & commctrl.HOTKEYF_SHIFT: result += 'Shift-'
             if mod & commctrl.HOTKEYF_CONTROL: result += 'Control-'
             if mod & commctrl.HOTKEYF_ALT: result += 'Alt-'
             result += chr ( hk % 256 )
        return result

Here's a typical usage pattern:

>>> shortcut = PyShortcut_II(  )
>>> shortcut.load(r'C:\WINDOWS\DESKTOP\Pygris.lnk' )
>>> shortcut.decode_hotkey(  )

7.17.3 Discussion

The ActiveState Python distribution includes an example that shows how to get and set Win32 shortcuts. This recipe shows how to extend the example to decode the hotkeys (such as Alt-Ctrl-Z and Shift-Ctrl-B) that can be associated with shortcuts.

On Win32, each shortcut can have an associated hotkey. In the link.py that is distributed as a demo with ActiveState's ActivePython, the hotkey is returned as a 16-bit code: the lower 8 bits encode the hotkey's characters, and the upper 8 bits encode modifiers, such as Shift, Control, and Alt. This recipe shows how to decode such a 16-bit code in terms of a printable key name for a shortcut's hotkey. Of course, this idea can also be useful for other similar needs, whenever key modifiers encoded as a bitmask using the bits named in the commctrl module need to be displayed readably.

7.17.4 See Also

Windows API documentation available from Microsoft (http://msdn.microsoft.com); the commctrl module is derived from the commctrl.h standard Windows include file.

    I l@ve RuBoard Previous Section Next Section