I am trying to achieve a functionality in which I can minimize other apps leaving only my current active window on my app using python. How can this be done?
A similar function is done using Windows + Home key, but how can I do this in my app?
Platform : WxPython
O.s : Windows
First, you need to pynput by using
pip install pynput
Now use this code to press Windows + Home key
from pynput.keyboard import Key, Controller
keyboard = Controller()
keyboard.press(Key.cmd)
keyboard.press(Key.home)
keyboard.release(Key.home)
keyboard.release(Key.cmd)
Then add delay to switch the app you want. Otherwise, it will keep only the python shell. I am adding 5 seconds delay you can change it as you want.
from pynput.keyboard import Key, Controller
from time import sleep
keyboard = Controller()
sleep(5) # this is 5 seconds change as you want
keyboard.press(Key.cmd)
keyboard.press(Key.home)
keyboard.release(Key.home)
keyboard.release(Key.cmd)
Related
I am trying to make a shortcut to open google when I do the function normal it works but when I try to do it in a shortcut it doesn't work.
import pyautogui as pg
import keyboard
hotkey1 = "ctrl+alt+w"
def google():
pg.hotkey("win")
pg.typewrite("google\n", 0.05)
while True:
if keyboard.is_pressed(hotkey1):
google()
You only need a pause until pg can take over. It so happens that when you press the hotkey combo, you might accidentally hit some other keys and therefore it doesn't work as intended. This should give it enough time for the key to be depressed before the automatic process starts.
import time
def google():
time.sleep(0.25)
pg.hotkey("win")
pg.typewrite("google\n", 0.05)
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
Hello I'm trying to simulate a mouse click while holding the SHIFT key. I have been trying to do this with the pynput module.
This is my code so far:
from pynput.keyboard import Key
from pynput.keyboard import Controller as Cont
from pynput.mouse import Button, Controller
import time
mouse = Controller()
keyboard = Cont()
with keyboard.pressed(Key.shift):
mouse.position = (1892, 838)
mouse.click(Button.left)
I know the code for holding the shift key is working (If I try to press the
"a" button in the code I see an "A"). Also I know the mouse click is working. However, together it does not work.
Also I tried another code from a StackOverflow post: Pyautogui - Need to hold shift and click
I tried the following code from it:
import pyautogui
pyautogui.keyDown('shift')
pyautogui.click()
pyautogui.keyUp('shift')
This worked for a minute then it stopped working! Very strange. It fails like 9 out of 10 times.
You should add a timer to it most likely will work.
import pyautogui
import time
#cordinates
cordinates = 100,100
pyautogui.keyDown('shift')
time.sleep(0.15)
pyautogui.click(cordinates)
time.sleep(0.15)
pyautogui.keyUp('shift')
The script works as intended, but it seems the target on which you are trying to apply Shift + Left-Click is not accepting such inputs while its window on Windows GUI is not in focus. That is why it works when you include a Left-Click before the Shift + Left-Click, because that first click puts the target window (whatever program/app it is) in focus, then the already working but ignored Shift + Left-Click is also accepted by the target
Well a workaround i suggest is creating an event listener like this :
from pynput.keyboard import Key, Listener
def on_press(key):
print('{0} pressed'.format(
key))
def on_release(key):
print('{0} release'.format(
key))
if key == Key.esc:
# Stop listener
return False
enter code hereCollect events until released
with Listener(
on_press=on_press,
on_release=on_release) as listener:
listener.join()
I created a short script using pyautogui module with the purpose of avoid a window 10 session to lock due to user but inactivity. But it's not working.
The script is moving the cursor a little each 120 sec.
Any idea why it's not working? Sometime ago I found on web a small program that was doing exactly the same thing and worked.
Let me just clarify that the script works (moving the mouse) but the windows 10 os locks anyway.
import pyautogui
import time
import win32gui, win32con
import os
Minimize = win32gui.GetForegroundWindow() #minimize current window
win32gui.ShowWindow(Minimize, win32con.SW_MINIMIZE) #minimize current window
x = 1
print("Application running...")
while x == 1:
pyautogui.moveRel(1) # move mouse 1 pixels down
time.sleep (120)
#end of script
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.