Python a good choice for experimenting with Win32 API?

sturlamolden sturlamolden at yahoo.no
Fri Sep 12 18:37:07 EDT 2008



> (1) Would CPython be a good choice for this? How about iron python? How
> about Jython (probably not).

You can use CPython without any problems. Alternatives are pywin32,
ctypes, cython, pyrex, Python C API.

You can use .NET platform invoke from IronPython.

You can use JNI from Jython, or any Win32 API wrapper that may exist
for Java.


> (2) What about callbacks? Which pythons can handle callbacks?

Yes you can use Python functions or bound methods as callbacks.


> (3) How easy it it define the C structs, enums and integer constants
> necessary to call the windows API functions?

It is easy if you can read C header files.


> (4) Here is the code I'm struggling with presently (it is just not
> cooperating: no errors just wrong results!

Here is what it will look like with the pywin32 package:


import win32api
import win32con

def compute(sLangId_, uCode_, uMapType_):
    hkl = win32api.LoadKeyboardLayout(sLangId_, win32con.KLF_ACTIVATE
        |win32con.KLF_SUBSTITUTE_OK|win32con.KLF_REPLACELANG)
    uResult_ = win32api.MapVirtualKeyEx(uCode_, uMapType_, hkl)
    return uResult_



With ctypes there is a little more work to do:


import ctypes

MAPVK_VK_TO_VSC = 0
MAPVK_VSC_TO_VK = 1
MAPVK_VK_TO_CHAR = 2
MAPVK_VSC_TO_VK_EX = 3
MAPVK_VK_TO_VSC_EX = 4
KLF_ACTIVATE = 1,
KLF_SUBSTITUTE_OK = 2
KLF_REORDER = 8
KLF_REPLACELANG = 0x10
KLF_NOTELLSHELL = 0x80
KLF_SETFORPROCESS = 0x00100
KLF_SHIFTLOCK = 0x10000
KLF_RESET = 0x40000000

LoadKeyboardLayout = ctypes.windll.user32.LoadKeyboardLayout
LoadKeyboardLayout.argtypes = (ctypes.c_wchar_p, ctypes.c_uint)
LoadKeyboardLayout.restype = ctypes.c_void_p

UnloadKeyboardLayout = ctypes.windll.user32.UnloadKeyboardLayout
UnloadKeyboardLayout.argtypes = (ctypes.c_void_p,)
UnloadKeyboardLayout.restype = ctypes.c_int

MapVirtualKeyEx = ctypes.windll.user32.UnloadKeyboardLayout
MapVirtualKeyEx.argtypes = (ctypes.c_uint, ctypes.c_uint,
ctypes.c_void_p)
MapVirtualKeyEx.restype = ctypes.c_uint

def compute(sLangId_, uCode_, uMapType_):
    hkl = LoadKeyboardLayout(sLangId_, KLF_ACTIVATE|KLF_SUBSTITUTE_OK|
KLF_REPLACELANG)
    uResult_ = MapVirtualKeyEx(uCode_, uMapType_, hkl)
    return uResult_

This is similar to your code, so it will have the same bugs.







More information about the Python-list mailing list