I want to minimize all open windows and / or show the desktop on a Windows 10 machine from within a python script. I had a look in the win32api, win32con, win32gui but cannot find anything appropriate.
Any idea appreciated. Thanks
Pyautogui is a great module for stimulating keyboard clicks and mouse clicks. To install it, try this command in the terminal. pip install PyAutoGUI
Using pyautogui, you can stimulate a virtual click in 2 ways. Choose which one works best for you:
1:
import pyautogui
pyautogui.hotkey('winleft', 'd')
2:
import pyautogui
pyautogui.keyDown('winleft')
pyautogui.press('d')
pyautogui.keyUp('winleft')
Sometimes the first one doesn't work, so if it doesn't, try the second one.
If you want to use WinApi to implement keyboard emulation, you can use the keybd_event function.
code:
import win32api
win32api.keybd_event(0x5B, 0, ) # LWIN
win32api.keybd_event(0x44, 0, ) # D
win32api.keybd_event(0x5B, 0, 2)
win32api.keybd_event(0x44, 0, 2)
Of course, you should probably use SendInput, but it is a bit complicated to use in python.
You can refer to this thread : How to generate keyboard events in Python?
Related
as the title says, I'm looking for a way to simulate horizontal scrolling (specifically in OneNote). I know it is possible to do it in AutoHotKey with a script, but I'm trying to keep the program as localized as possible. I also know it is possible with PyAutoGui on mac and linux, but I've come up empty handed with anything related to windows. If you have any leads, I would greatly appreciate it:)
For anyone running into a similar problem in the future, here's my solution:
import win32api, time, pyautogui as pag, keyboard
from win32con import *
running = True
lastX, lastY = pag.position()
while running:
while keyboard.is_pressed("shift"):
x, y = pag.position()
if lastX!=x:
win32api.mouse_event(MOUSEEVENTF_HWHEEL, 0, 0, x-lastX, 0) # Horizontal scrolling
lastX=x
if lastY!=y:
win32api.mouse_event(MOUSEEVENTF_WHEEL, 0, 0, lastY-y, 0) # Vertical scrolling
lastY=y
Hope this can help anyone in the future:)
Windows 10 already has an out-of-the-box shortcut for horizontal scroll:
Hold Shift down and use the mouse wheel for side scroll. (This shortcut seems to also work on Ubuntu und MacOS)
Considering this shortcut exists it is possible to emulate it with PyAutoGui like so
import pyautogui
offset = 100
pyautogui.keyDown('shift')
pyautogui.scroll(offset)
pyautogui.keyUp('shift')
I am trying to write a python script that will type out lines from a text document as if they were coming from a keyboard.
I already have a code snippet working in some apps (see below), and this types every line from the file I open correctly, I tested the output into notepad++ for example and it types it all out.
import keyboard
import time
time.sleep(3) """ this gives me enough time to alt-tab into the game (Witcher 3)
that I am trying to have the keypresses inserted into, I also tried some code with
win32gui that brough the Witcher 3 app to the front, but this is simpler. """
with open('w3recipes.txt', 'r', encoding='utf-8') as recipes:
for line in recipes:
keyboard.write(line)
time.sleep(0.05)
The issue is that these keystrokes are not registered by Witcher 3, the game I am trying to write all these keystrokes to. I tried changing the game from fullscreen to windowed with no luck, and I tried compiling the script to a .exe and running it as an admin as well, no dice. I also tried the pynput library as opposed to the keyboard library used here and that yielded the same result.
Any help would be appreciated, I am trying to write a few hundred console commands to this game and there is no newline character in the game's console; it only supports 1 command at a time before hitting enter. My only other option is sitting here copy-pasting all the lines in which would be tiresome.
Thanks in advance.
Use another library, pydirectinput. It's an updated version of pyautogui, and I've found it works with most (if not all) games.
Quoting from docs:
This library aims to replicate the functionality of the PyAutoGUI mouse and keyboard inputs, but by utilizing DirectInput scan codes and the more modern SendInput() win32 function. PyAutoGUI uses Virtual Key Codes (VKs) and the deprecated mouse_event() and keybd_event() win32 functions. You may find that PyAutoGUI does not work in some applications, particularly in video games and other software that rely on DirectX. If you find yourself in that situation, give this library a try!
Write functions:
>>> import pyautogui
>>> import pydirectinput
>>> pydirectinput.moveTo(100, 150) # Move the mouse to the x, y coordinates 100, 150.
>>> pydirectinput.click() # Click the mouse at its current location.
>>> pydirectinput.click(200, 220) # Click the mouse at the x, y coordinates 200, 220.
>>> pydirectinput.move(None, 10) # Move mouse 10 pixels down, that is, move the mouse relative to its current position.
>>> pydirectinput.doubleClick() # Double click the mouse at the
>>> pydirectinput.press('esc') # Simulate pressing the Escape key.
>>> pydirectinput.keyDown('shift')
>>> pydirectinput.keyUp('shift')
# And this is the one you want,
>>> pydirectinput.write('string') # Write string
>>> pydirectinput.typewrite("string")
I tried to use this script to prevent windows screen lock. The script works for moving the mouse, but it doesn't prevent windows 10 from locking.
import pyautogui
import time
import win32gui, win32con
import os
Minimize = win32gui.GetForegroundWindow()
win32gui.ShowWindow(Minimize, win32con.SW_MINIMIZE)
x = 1
while x == 1:
pyautogui.moveRel(1)
pyautogui.moveRel(-1)
time.sleep (300)
Yes it can. But sadly not by moving mouse which I don't know why and would like to know. So, my suggestion is to use pyautogui KEYBOARD EVENTS if possible. I have solved my problems by using VOLUME-UP & VOLUME-DOWN keys. Example code is provided below:
import pyautogui
import time
while True:
pyautogui.press('volumedown')
time.sleep(1)
pyautogui.press('volumeup')
time.sleep(5)
You can use any other keys if you want.
import ctypes
# prevent
ctypes.windll.kernel32.SetThreadExecutionState(0x80000002)
# set back to normal
ctypes.windll.kernel32.SetThreadExecutionState(0x80000000)
https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-setthreadexecutionstate
Tested on python 3.9.1, win 10 64bit
I need to do some macros and I wanna know what is the most recommended way to do it.
So, I need to write somethings and click some places with it and I need to emulate the TAB key to.
I do automated testing stuff in Python. I tend to use the following:
http://www.tizmoi.net/watsup/intro.html
Edit: Link is dead, archived version: https://web.archive.org/web/20100224025508/http://www.tizmoi.net/watsup/intro.html
http://www.mayukhbose.com/python/IEC/index.php
I do not always (almost never) simulate key presses and mouse movement. I usually use COM to set values of windows objects and call their .click() methods.
You can send keypress signals with this:
import win32com.client
shell = win32com.client.Dispatch("WScript.Shell")
shell.SendKeys("^a") # CTRL+A may "select all" depending on which window's focused
shell.SendKeys("{DELETE}") # Delete selected text? Depends on context. :P
shell.SendKeys("{TAB}") #Press tab... to change focus or whatever
This is all in Windows. If you're in another environment, I have no clue.
Maybe you are looking for Sendkeys?
SendKeys is a Python module for
Windows that can send one or more
keystrokes or keystroke combinations
to the active window.
it seems it is windows only
Also you have pywinauto (copied from my SO answer)
pywinauto is a set of open-source
(LGPL) modules for using Python as a
GUI automation 'driver' for Windows NT
based Operating Systems (NT/W2K/XP).
and example from the web page
> from pywinauto import application
> app = application.Application.start("notepad.exe")
> app.notepad.TypeKeys("%FX")
> app.Notepad.MenuSelect("File->SaveAs")
> app.SaveAs.ComboBox5.Select("UTF-8")
> app.SaveAs.edit1.SetText("Example-utf8.txt")
> app.SaveAs.Save.Click()
pyautogui is a great package to send keys and automate several keyboard / mouse related tasks. Check out Controlling the Keyboard and Mouse with GUI Automation and PyAutoGUI’s documentation.
You can use PyAutoGUI library for Python which works on Windows, macOS, and Linux.
Mouse
Here is a simple code to move the mouse to the middle of the screen:
import pyautogui
screenWidth, screenHeight = pyautogui.size()
pyautogui.moveTo(screenWidth / 2, screenHeight / 2)
Docs page: Mouse Control Functions.
Related question: Controlling mouse with Python.
Keyboard
Example:
pyautogui.typewrite('Hello world!') # prints out "Hello world!" instantly
pyautogui.typewrite('Hello world!', interval=0.25) # prints out "Hello world!" with a quarter second delay after each character
Docs page: Keyboard Control Functions.
More reading: Controlling the Keyboard and Mouse with GUI Automation (Chapter 18 of e-book).
Related questions:
Python GUI automation library for simulating user interaction in apps.
Python simulate keydown.
Two other options are:
pynput - https://pypi.org/project/pynput/ - which is for Windows (tested), Linux and MacOS- docs are at https://pynput.readthedocs.io/en/latest/
PyDirectInput - https://pypi.org/project/PyDirectInput/ - which is for Windows only and can be used with (or without) PyAutoGUI
Warning - if you are wanting to use keyboard control for games, then pynput doesn't always work - e.g. it works for Valheim, but not for the Witcher 3 - which is where PyDirectInput will work instead. I also tested PyDirectInput and it works for Half life 2 (as a test of an older game).
Tip - You will likely need to reduce (don't remove for games) the delay between character typing - use pydirectinput.PAUSE = 0.05
As an example, here is a function that allows virtual keyboard typing - currently only tested on Windows:
from pynput import keyboard
try:
import pydirectinput
pydirectinput.PAUSE = 0.05
except ImportError as err:
pydirectinput = False
print("pydirectinput not found:")
def write_char(ch):
upper = ch.isupper()
if pydirectinput and pydirectinput.KEYBOARD_MAPPING.get(ch.lower(), False):
if upper:
pydirectinput.keyDown('shift')
print('^')
pydirectinput.write(ch.lower(), interval=0.0)
print(ch)
if upper:
pydirectinput.keyUp('shift')
else:
keyboard.Controller().type(ch)
This allows a string to be sent in, with upper case alphabetic characters handled through pydirectinput. When characters don't simply map, the function falls back to using pynput. Note that PyAutoGUI also can't handled some shifted characters - such as the £ symbol, etc.
I need to do some macros and I wanna know what is the most recommended way to do it.
So, I need to write somethings and click some places with it and I need to emulate the TAB key to.
I do automated testing stuff in Python. I tend to use the following:
http://www.tizmoi.net/watsup/intro.html
Edit: Link is dead, archived version: https://web.archive.org/web/20100224025508/http://www.tizmoi.net/watsup/intro.html
http://www.mayukhbose.com/python/IEC/index.php
I do not always (almost never) simulate key presses and mouse movement. I usually use COM to set values of windows objects and call their .click() methods.
You can send keypress signals with this:
import win32com.client
shell = win32com.client.Dispatch("WScript.Shell")
shell.SendKeys("^a") # CTRL+A may "select all" depending on which window's focused
shell.SendKeys("{DELETE}") # Delete selected text? Depends on context. :P
shell.SendKeys("{TAB}") #Press tab... to change focus or whatever
This is all in Windows. If you're in another environment, I have no clue.
Maybe you are looking for Sendkeys?
SendKeys is a Python module for
Windows that can send one or more
keystrokes or keystroke combinations
to the active window.
it seems it is windows only
Also you have pywinauto (copied from my SO answer)
pywinauto is a set of open-source
(LGPL) modules for using Python as a
GUI automation 'driver' for Windows NT
based Operating Systems (NT/W2K/XP).
and example from the web page
> from pywinauto import application
> app = application.Application.start("notepad.exe")
> app.notepad.TypeKeys("%FX")
> app.Notepad.MenuSelect("File->SaveAs")
> app.SaveAs.ComboBox5.Select("UTF-8")
> app.SaveAs.edit1.SetText("Example-utf8.txt")
> app.SaveAs.Save.Click()
pyautogui is a great package to send keys and automate several keyboard / mouse related tasks. Check out Controlling the Keyboard and Mouse with GUI Automation and PyAutoGUI’s documentation.
You can use PyAutoGUI library for Python which works on Windows, macOS, and Linux.
Mouse
Here is a simple code to move the mouse to the middle of the screen:
import pyautogui
screenWidth, screenHeight = pyautogui.size()
pyautogui.moveTo(screenWidth / 2, screenHeight / 2)
Docs page: Mouse Control Functions.
Related question: Controlling mouse with Python.
Keyboard
Example:
pyautogui.typewrite('Hello world!') # prints out "Hello world!" instantly
pyautogui.typewrite('Hello world!', interval=0.25) # prints out "Hello world!" with a quarter second delay after each character
Docs page: Keyboard Control Functions.
More reading: Controlling the Keyboard and Mouse with GUI Automation (Chapter 18 of e-book).
Related questions:
Python GUI automation library for simulating user interaction in apps.
Python simulate keydown.
Two other options are:
pynput - https://pypi.org/project/pynput/ - which is for Windows (tested), Linux and MacOS- docs are at https://pynput.readthedocs.io/en/latest/
PyDirectInput - https://pypi.org/project/PyDirectInput/ - which is for Windows only and can be used with (or without) PyAutoGUI
Warning - if you are wanting to use keyboard control for games, then pynput doesn't always work - e.g. it works for Valheim, but not for the Witcher 3 - which is where PyDirectInput will work instead. I also tested PyDirectInput and it works for Half life 2 (as a test of an older game).
Tip - You will likely need to reduce (don't remove for games) the delay between character typing - use pydirectinput.PAUSE = 0.05
As an example, here is a function that allows virtual keyboard typing - currently only tested on Windows:
from pynput import keyboard
try:
import pydirectinput
pydirectinput.PAUSE = 0.05
except ImportError as err:
pydirectinput = False
print("pydirectinput not found:")
def write_char(ch):
upper = ch.isupper()
if pydirectinput and pydirectinput.KEYBOARD_MAPPING.get(ch.lower(), False):
if upper:
pydirectinput.keyDown('shift')
print('^')
pydirectinput.write(ch.lower(), interval=0.0)
print(ch)
if upper:
pydirectinput.keyUp('shift')
else:
keyboard.Controller().type(ch)
This allows a string to be sent in, with upper case alphabetic characters handled through pydirectinput. When characters don't simply map, the function falls back to using pynput. Note that PyAutoGUI also can't handled some shifted characters - such as the £ symbol, etc.