Python Pynput hotkey issue involving easygui window - python

I wrote some code to help to copy and paste multiple lines in a program that doesn't allow you to copy and paste multiple rows nicely like excel does. I've tried writing this tool in AHK but something about AHK doesn't seem to play nice with the program in question (RSLogix studio 5000, AHK always misses lines when copy and pasting). This python code works nicely and doesn't miss lines when copying or pasting, but I've encountered a new issue. Despite what I've set the hotkeys to (ctrl 1 brings up a window asking how many lines you'd like to copy or paste, ctrl 2 copies that many lines, ctrl 3 pastes that many lines) pressing ctrl always brings up the input window. If I remove the input window and hardcode the value for "lines" then everything works as expected. Something about this window is making the program act strangely. Does anyone have any ideas?
thanks in advance for your time:)
import pyautogui
import easygui
import keyboard
import pyperclip
import time
from pynput.keyboard import HotKey, Key, KeyCode, Listener
from pynput import keyboard
copy_list=[]
lines = 0
def function_1():
global lines
lines = easygui.integerbox("Enter number of lines to copy")
print(lines)
def function_2():
global lines
copy_list.clear()
for x in range(int(lines)):
pyautogui.hotkey('ctrl', 'c')
clp=pyperclip.paste()
pyperclip.copy("")
copy_list.append(clp)
pyautogui.press('down')
print(copy_list)
def function_3():
global lines
for x in range(int(lines)):
pyperclip.copy(copy_list[x])
pyautogui.hotkey('ctrl', 'v')
pyautogui.press('enter',presses=3,interval=0.05)
with keyboard.GlobalHotKeys({
'<ctrl>+1': function_1,
'<ctrl>+2': function_2,
'<ctrl>+3': function_3}) as h:
h.join()

Related

Trying to accept the keyboard input 'R' alone or along side any other amount of keyboard inputs using either keyboard or pygame modules

import keyboard
import pygame
import mouse
import time
def press_X():
time.sleep(0.2)
keyboard.press('x')
time.sleep(0.6)
keyboard.release('x')
print('Command Executed - press_X')
#SA_R_X V_1.0
#------------------------------------------
while True:
try:
keyboard.add_hotkey('r', press_X)
time.sleep(0.5)
break
except:
keyboard.add_hotkey('r', press_X)
time.sleep(0.5)
break
the problem is the code cannot detect if 'r' is pressed when i am holding 'w' and/or 'space'... (well any key really)
I tried to use a try and except to handle a combination of any key + 'r'. But it did not work. All I need is for the code to be able to detect an 'r' input even if I am pressing/ holding another key at the same time. Then after this the code waits 0.2 seconds before holding down the 'x' key for 0.6 seconds and releasing. Any help is appreciated and it would be very helpful if you included a short explanation on where I went wrong and how you fixed it.
The documentation for this module can be found here. This is where all relevant information can be found.
The best way to do this, from my understanding, is to use an alternative function. If you want the program to continue to run, even though the key has not been pressed, then I suggest using the keyboard.on_press_key() function. This would mean that the rest of your program could still run, and your press_X() function could be run as a callback. Here is an example of how this code could be implemented.
import keyboard
import pygame
import mouse
import time
class App:
running = True
def press_X():
time.sleep(0.2)
keyboard.press('x')
time.sleep(0.6)
keyboard.release('x')
print('Command Executed - press_X')
App.running = False
#SA_R_X V_1.0
#------------------------------------------
keyboard.on_press_key('r', lambda x: press_X()) ## Adds an event listener for the r key
## This will stop execution if there is no code after this point
If you want it to stop the program and wait for the r key to be pressed, then you could use keyboard.wait(). This will basically pause your program until the key is pressed, after which your function would be run. For example, to replace the keyboard.on_press_key('r', lambda x: press_X()):
keyboard.wait('r')
press_X()
From my understanding, keyboard.add_hotkey() does not work in your situation because it is looking for an exact combination of keys being pressed, such as Ctrl+C, and will only go if only the keys in the hotkey are pressed.
I hope this helps, good luck!

How to make KeyboardInterrupt outside of console?

I'm using PyAutoGui for automation of adding data to certain fullscreen app. Problem is, when I try to Alt+Tab back to my IDE it constantly brings app back to front and messes up my code by pasting data there. I need a way to either prevent script from working when I press Alt+Tab or when window comes out of focus. How do I do that?
I tried:
Ctrl-C
Ctrl-Pause
import _thread
def input_thread(a_list):
raw_input() # use input() in Python3
a_list.append(True)
def do_stuff():
a_list = []
_thread.start_new_thread(input_thread, (a_list,))
while not a_list:
stuff()

Making keyboard shortcut, but it does not do anything

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)

Pynput and pyAutoGui can't hold keys

I wanted to make a simple macro to hold down 'W' for some time, but even simple script like this does not work.
import time
import pyautogui
from pynput.keyboard import Key, Controller
keyboard = Controller()
pyautogui.keyDown('w')
time.sleep(3)
pyautogui.keyUp('w')
time.sleep(5)
keyboard.press('w')
time.sleep(3)
keyboard.release('w')
If i test it in any text editor/text input window it will write one 'w' when script starts and anouther one after 8 seconds without holding/spaming it. And therefore it DOES NOT work in any games what should be the whole purpose of this script. I tried it in a huge variety of different games (Java Minecraft, source Gmod, Roblox and some unity games) and this script just was not working in any of them, but if a game has chat, search box or any other text input window, this script will write one 'w' and anouther one after some time in it.
I realy have no idea why this is happening, but i remembered that two years ago i tried to make similar script on pynput and it did work, so i tried installing old versions of pynput, but that did not help me as well...
So after a long time i could finaly take care of the issue, and i figured out that the source of the problem was in the Microsoft's DirectInput. Basically pynput and pyAutoGUI are not able to get in to DirectInput and there is no signal at all while I thought that there wwas a signal, but for so little amount of time that the games just were not able to pick it up. And the solution to this was pretty easy thanks to this guy PyAutoGUI not working? Use DirectInput. Thanks to his PyDirectInput librarry you are able to use python to emulate button presses and holdes in games!
This might be a start to work with:
#https://stackoverflow.com/questions/66284097/pynput-and-pyautogui-cant-hold-keys
#simulate keystroke for some amount of time
import msvcrt
import time
def press(char, duration, sleep, limit=None):
while True:
lim = limit
t1 = time.time()
while time.time() - t1 < duration: # do for duration specified
msvcrt.putch(char) # output character, putch() awaits a byte string
if lim: # limit specified?
lim -= 1
if lim == 0: # limit reached
break
time.sleep(SLEEP)
if msvcrt.kbhit(): # key pressed?
char = msvcrt.getch()
press(b'w', .001, 2, None)

Pressing keys with python win32api

I am trying to achieve the following behavior in a PYTHON 2.4 script, here are the steps, and after them, the question:
Python script starts
The script gives a 3 seconds delay to change to 'Z' program's window
The script does some clicks on the 'Z' program's window.
The script stops making clicks
/* ¿? */
Ask to continue with the program's excecution
/* ¿? */
Go to step 2
So, in steps 5 and 7 what I want to do is simulate the pressing of keys Alt+Tab in order to go back to the script window (in step 5), and go back again to the 'Z' program's window (in step 7).
And the problem is that I have no idea how to achieve this (the simulation to press keys alt+tab), and didn't find answers to my doubts.
I am using the python win32api modules to positionate mouse in a certain point and make the clicks, but I don't find the way to simulate the key pressing.
Try This :
1) Use : https://gist.github.com/chriskiehl/2906125
2)
import win32api
import win32com.client
shell = win32com.client.Dispatch("WScript.Shell")
shell.Run("app")
win32api.Sleep(100)
shell.AppActivate("myApp")
win32api.Sleep(100)
shell.SendKeys("name")
win32api.Sleep(500)
shell.SendKeys("{ENTER}")
win32api.Sleep(2500)
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
You need the WinApi function SendInput.
See the description in the MSDN:
http://msdn.microsoft.com/en-us/library/windows/desktop/ms646310(v=vs.85).aspx
An Easier Way
Use this Library W32S
My Library.
And If u want , just copy the source instead

Categories

Resources