How to generate keyboard events?
It can be done using ctypes:
import ctypes
from ctypes import wintypes
import time
user32 = ctypes.WinDLL('user32', use_last_error=True)
INPUT_MOUSE = 0
INPUT_KEYBOARD = 1
INPUT_HARDWARE = 2
KEYEVENTF_EXTENDEDKEY = 0x0001
KEYEVENTF_KEYUP = 0x0002
KEYEVENTF_UNICODE = 0x0004
KEYEVENTF_SCANCODE = 0x0008
MAPVK_VK_TO_VSC = 0
# msdn.microsoft.com/en-us/library/dd375731
VK_TAB = 0x09
VK_MENU = 0x12
# C struct definitions
wintypes.ULONG_PTR = wintypes.WPARAM
class MOUSEINPUT(ctypes.Structure):
_fields_ = (("dx", wintypes.LONG),
("dy", wintypes.LONG),
("mouseData", wintypes.DWORD),
("dwFlags", wintypes.DWORD),
("time", wintypes.DWORD),
("dwExtraInfo", wintypes.ULONG_PTR))
class KEYBDINPUT(ctypes.Structure):
_fields_ = (("wVk", wintypes.WORD),
("wScan", wintypes.WORD),
("dwFlags", wintypes.DWORD),
("time", wintypes.DWORD),
("dwExtraInfo", wintypes.ULONG_PTR))
def __init__(self, *args, **kwds):
super(KEYBDINPUT, self).__init__(*args, **kwds)
# some programs use the scan code even if KEYEVENTF_SCANCODE
# isn't set in dwFflags, so attempt to map the correct code.
if not self.dwFlags & KEYEVENTF_UNICODE:
self.wScan = user32.MapVirtualKeyExW(self.wVk,
MAPVK_VK_TO_VSC, 0)
class HARDWAREINPUT(ctypes.Structure):
_fields_ = (("uMsg", wintypes.DWORD),
("wParamL", wintypes.WORD),
("wParamH", wintypes.WORD))
class INPUT(ctypes.Structure):
class _INPUT(ctypes.Union):
_fields_ = (("ki", KEYBDINPUT),
("mi", MOUSEINPUT),
("hi", HARDWAREINPUT))
_anonymous_ = ("_input",)
_fields_ = (("type", wintypes.DWORD),
("_input", _INPUT))
LPINPUT = ctypes.POINTER(INPUT)
def _check_count(result, func, args):
if result == 0:
raise ctypes.WinError(ctypes.get_last_error())
return args
user32.SendInput.errcheck = _check_count
user32.SendInput.argtypes = (wintypes.UINT, # nInputs
LPINPUT, # pInputs
ctypes.c_int) # cbSize
# Functions
def PressKey(hexKeyCode):
x = INPUT(type=INPUT_KEYBOARD,
ki=KEYBDINPUT(wVk=hexKeyCode))
user32.SendInput(1, ctypes.byref(x), ctypes.sizeof(x))
def ReleaseKey(hexKeyCode):
x = INPUT(type=INPUT_KEYBOARD,
ki=KEYBDINPUT(wVk=hexKeyCode,
dwFlags=KEYEVENTF_KEYUP))
user32.SendInput(1, ctypes.byref(x), ctypes.sizeof(x))
def AltTab():
"""Press Alt+Tab and hold Alt key for 2 seconds
in order to see the overlay.
"""
PressKey(VK_MENU) # Alt
PressKey(VK_TAB) # Tab
ReleaseKey(VK_TAB) # Tab~
time.sleep(2)
ReleaseKey(VK_MENU) # Alt~
if __name__ == "__main__":
AltTab()
hexKeyCode
is the virtual keyboard mapping as defined by the Windows API. The list of codes is available on MSDN: Virtual-Key Codes (Windows)
Generate keyboard events for the frontmost application
Sure, you'll want to use CGEventCreateKeyboardEvent to create keyboard events, then post them as such:
CGEventRef keyup, keydown;
keydown = CGEventCreateKeyboardEvent (NULL, (CGKeyCode)56, true);
keyup = CGEventCreateKeyboardEvent (NULL, (CGKeyCode)56, false);
CGEventPost(kCGHIDEventTap, keydown);
CGEventPost(kCGHIDEventTap, keyup);
CFRelease(keydown);
CFRelease(keyup);
It's a bit more complicated than AppleScript but it does the trick. You do have to explicitly post a keydown and then a keyup event. More information at the Quartz Event Services Reference.
How to generate keypress event programmatically
Have a look at this article, particularly the following snippet of code:
/* synthesize Alt+O key press */
event = gdk_event_new (GDK_KEY_PRESS);
event->key.window = widget->window;
This line should actually read:
event->key.window = g_object_ref (widget->window);
Otherwise you'll get interesting error messages later on if you destroy
widgets. Took some time to figure out for myself. :)
Can we simulate a key press without an event handler?
window.find(…)
does that.
In general, you're out of luck though trying to orchestrate native browser functionality from within a webpage. Browser extensions can do more.
How can I programmatically generate keypress events in C#?
The question is tagged WPF but the answers so far are specific WinForms and Win32.
To do this in WPF, simply construct a KeyEventArgs and call RaiseEvent on the target. For example, to send an Insert key KeyDown event to the currently focused element:
var key = Key.Insert; // Key to send
var target = Keyboard.FocusedElement; // Target element
var routedEvent = Keyboard.KeyDownEvent; // Event to send
target.RaiseEvent(
new KeyEventArgs(
Keyboard.PrimaryDevice,
PresentationSource.FromVisual(target),
0,
key)
{ RoutedEvent=routedEvent }
);
This solution doesn't rely on native calls or Windows internals and should be much more reliable than the others. It also allows you to simulate a keypress on a specific element.
Note that this code is only applicable to PreviewKeyDown, KeyDown, PreviewKeyUp, and KeyUp events. If you want to send TextInput events you'll do this instead:
var text = "Hello";
var target = Keyboard.FocusedElement;
var routedEvent = TextCompositionManager.TextInputEvent;
target.RaiseEvent(
new TextCompositionEventArgs(
InputManager.Current.PrimaryKeyboardDevice,
new TextComposition(InputManager.Current, target, text))
{ RoutedEvent = routedEvent }
);
Also note that:
Controls expect to receive Preview
events, for example PreviewKeyDown
should precede KeyDownUsing target.RaiseEvent(...) sends the event directly to the target
without meta-processing such as
accelerators, text composition and
IME. This is normally what you want.
On the other hand, if you really do
what to simulate actual keyboard keys
for some reason, you would use
InputManager.ProcessInput() instead.
Related Topics
How to Access Command Line Arguments
Importerror: No Module Named 'Tkinter'
Create Pandas Dataframe from Txt File with Specific Pattern
Different Behaviour for List._Iadd_ and List._Add_
Importerror: No Module Named 'Encodings'
How to Start a Python File While Windows Starts
How to Fix Overlapping Annotations/Text
Pandas Long to Wide Reshape, by Two Variables
Max Retries Exceeded with Url in Requests
Generate 'N' Unique Random Numbers Within a Range
Reading a Utf8 CSV File with Python
How to Get Variable Data from a Class
Is It Pythonic: Naming Lambdas
Display a Decimal in Scientific Notation