Skip to content

Instantly share code, notes, and snippets.

@bean-mhm
Created June 2, 2023 21:25
Show Gist options
  • Select an option

  • Save bean-mhm/2cbb4901431f281ff2c493c20e8b798d to your computer and use it in GitHub Desktop.

Select an option

Save bean-mhm/2cbb4901431f281ff2c493c20e8b798d to your computer and use it in GitHub Desktop.
Save Screenshot Directly to Desktop with Hotkey (Windows-Only)
# python -m pip install --upgrade pywin32
# pip install pyautogui
import win32con, ctypes, ctypes.wintypes
import pyautogui
from datetime import datetime
# Your Windows username (to determine the desktop path)
windows_username = 'user'
# Hotkey
hotkey_mod = win32con.MOD_WIN
hotkey_vk = win32con.VK_F2
def hotkey_pressed():
# Take screenshot
screenshot = pyautogui.screenshot()
# Determine the filename
now = datetime.now()
filename_short = f'Screenshot {now.hour}_{now.minute}_{now.second}_{now.microsecond // 1000}.png'
filename = f'C:\\Users\{windows_username}\\Desktop\\{filename_short}'
# Save the screenshot
screenshot.save(filename)
# Print
print(f'Saved {filename_short}')
# Register the hotkey
ctypes.windll.user32.RegisterHotKey(None, 1, hotkey_mod, hotkey_vk)
# Wait for the hotkey
print('Listening for the hotkey...')
try:
msg = ctypes.wintypes.MSG()
while ctypes.windll.user32.GetMessageA(ctypes.byref(msg), None, 0, 0) != 0:
if msg.message == win32con.WM_HOTKEY:
hotkey_pressed()
ctypes.windll.user32.TranslateMessage(ctypes.byref(msg))
ctypes.windll.user32.DispatchMessageA(ctypes.byref(msg))
finally:
ctypes.windll.user32.UnregisterHotKey(None, 1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment