Skip to content

Instantly share code, notes, and snippets.

@brccabral
Last active October 17, 2023 17:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brccabral/ebd738cfd177bf62ffd8ce0ef8ada36d to your computer and use it in GitHub Desktop.
Save brccabral/ebd738cfd177bf62ffd8ce0ef8ada36d to your computer and use it in GitHub Desktop.
Keystroke

Keystroke

C++

Linux

Send a keystroke to focused window.
Compile with -lX11 -lXtst

Python

sudo apt install scrot
pip install pyautogui
cmake_minimum_required(VERSION 3.21)
project(Keystroke)
include(GNUInstallDirs)
add_executable(${PROJECT_NAME} main.cpp)
target_link_libraries(${PROJECT_NAME} PUBLIC X11 Xtst)
install(TARGETS ${PROJECT_NAME})
#include <stdio.h>
#include <X11/Xlib.h>
#include <X11/Intrinsic.h>
#include <X11/extensions/XTest.h>
#include <unistd.h>
#include <iostream>
#include <X11/keysymdef.h>
int main() {
Display *dis;
dis = XOpenDisplay(NULL);
if(dis == NULL)
{
std::cout << "Can't open display" << std::endl;
return 1;
}
KeyCode modcode = 0; //init value
std::cout << "Select window" << std::endl;
sleep(2);
std::cout << "Sending keys" << std::endl;
for (int i=0;i<5;i++) {
// modcode = XKeysymToKeycode(dis, XStringToKeysym("a"));
modcode = XKeysymToKeycode(dis, XK_a);
XTestFakeKeyEvent(dis, modcode, False, 0);
XFlush(dis);
sleep(1);
XTestFakeKeyEvent(dis, modcode, True, 0);
XFlush(dis);
XTestFakeKeyEvent(dis, modcode, False, 0);
XFlush(dis);
}
return 0;
}
import pyautogui
# Type with quarter-second pause in between each key.
pyautogui.write("Hello world!", interval=0.25)
# Returns two integers, the width and height of the screen. (The primary monitor, in multi-monitor setups.)
screenWidth, screenHeight = pyautogui.size()
# Returns two integers, the x and y of the mouse cursor's current position.
currentMouseX, currentMouseY = pyautogui.position()
# Move the mouse to the x, y coordinates 100, 150.
pyautogui.moveTo(100, 150)
# Click the mouse at its current location.
pyautogui.click()
# Click the mouse at the x, y coordinates 200, 220.
pyautogui.click(200, 220)
# Move mouse 10 pixels down, that is, move the mouse relative to its current position.
pyautogui.move(None, 10)
# Double click the mouse at the
pyautogui.doubleClick()
# Use tweening/easing function to move mouse over 2 seconds.
# # pip install pytweening
# # pyautogui.moveTo(500, 500, duration=2, tween=pyautogui.easeInOutQuad)
# Simulate pressing the Escape key.
pyautogui.press("esc")
pyautogui.keyDown("shift")
pyautogui.write(["left", "left", "left", "left", "left", "left"])
pyautogui.keyUp("shift")
pyautogui.hotkey("ctrl", "c")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment