1. Anuncie Aqui ! Entre em contato fdantas@4each.com.br

[Python] How to wrap the SendInput function to python using ctypes

Discussão em 'Python' iniciado por Stack, Outubro 7, 2024.

  1. Stack

    Stack Membro Participativo

    I am trying to get the SendInput function from user32.dll to work in python using ctypes.I am a noob but from what I read from the docs you have to create the structs the function requires in python and then pass it to the function.

    import ctypes
    import keyboard
    from ctypes import *
    lib = windll.user32

    KEYEVENTF_SCANCODE = 0x8
    KEYEVENTF_KEYUP = 0x2
    SPACEBAR = 57 # 0x39
    INPUT_KEYBOARD = 1


    class KEYBDINPUT(Structure):
    _fields_ = [('wVk' , c_ushort) , ('wScan' , c_ushort)
    , ('dwFlags' , c_ulong) , ('time' , c_ulong) , ('dwExtraInfo' , c_ulong)]
    class INPUT(Structure):
    _fields_ = [('type' , c_ulong) ,('ki' , KEYBDINPUT)]


    lib.SendInput.restype = c_uint
    lib.SendInput.argtypes = [c_uint , INPUT , c_int]

    keybdinput_obj = KEYBDINPUT(0 , SPACEBAR , KEYEVENTF_SCANCODE , 0 , 0)
    input_obj = INPUT(INPUT_KEYBOARD , keybdinput_obj)
    keyboard.wait('u')
    lib.SendInput(1 , byref(input_obj) , sizeof(INPUT))
    keybdinput_obj = KEYBDINPUT(0 , SPACEBAR , KEYEVENTF_SCANCODE | KEYEVENTF_KEYUP , 0 , 0)
    input_obj = INPUT(INPUT_KEYBOARD , keybdinput_obj)
    lib.SendInput(1 , byref(input_obj) , sizeof(INPUT))


    In the microsoft docs at which I guided myself from the INPUT struct had an union but i figured if I would only need the KEYBDINPUT then it's the same thing as if i had an union.

    https://learn.microsoft.com/en-us/windows/win32/api/winuser/ns-winuser-input

    https://learn.microsoft.com/en-us/windows/win32/api/winuser/ns-winuser-keybdinput

    https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-sendinput

    I pretty much got stuck because i can't see what's going wrong here so I am asking for help.The program is supposed to send a space after i press 'u' on the keyboard (this was for debugging purposes) and i do it this way because i want it to send as a scancode instead of a virtual keypress.

    So if there is another way in python with with which you can send scancodes , that'll work and I would appreciate it a lot .

    Continue reading...

Compartilhe esta Página