How to control windows in windows 10 with python3 - python-3.x

I am looking for a good way to get window information to find and close them programmatically.
i have been using pywinauto and pyautogui. brining all of my knowledge from autoit.
Using python3 autoit has not been working.
From Python3 we hope to accomplish: Here is the AutoIT command to translate to python3
If WinExists("WindowName") then
WinClose("WindowName")

Thank you for all your help everyone, I seem to have found a good solution. Hopefully this will help someone else as well!
This connects the application to Pywinauto:
import pywinauto as pwa
app = pwa.application.Application(backend="uia")
app.connect(path='AppName.exe')
Here we are creating a dialog for the app window and specifying a name reference.
dlg = app.window(title_re=".*AppName.*")
In this area, we are calling the window, and wait for it to be ready. Then we are going to close the window.
dlg.child_window(title="WindowName", control_type="Window").wait('ready', timeout=10):
dlg.child_window(title="WindowName", control_type="Window").close()
print("Window is closed")

Related

Selenium Python - Internet Explorer - Problem

I'm new on Selenium and I'm trying to do a task using Internet Explorer (I'm using Python 3.8)
In order to uderstand the commands of Selenium, I tried to run the simple code below
from selenium.webdriver.common.keys import Keys
import time
driver=webdriver.Ie(executable_path="C:\\Users\\usuario\\Downloads\\IEDriverServer.exe")
driver.get("https://www.google.com.br/")
driver.set_page_load_timeout(10)
driver.find_element_by_name("q").send_keys("Ronaldinho Gaucho")
driver.find_element_by_name("btnK").send_keys(Keys.ENTER)
driver.maximize_window()
driver.refresh()
The page opens, however, nothing is typed on the search bar on Google website, I have seen this code in a Youtube video and it has worked well, but when I try on my computer, it does not works (it does not raise any error on my terminal)
Anyone can help?, what I should been looking for?
Thanks in advance

Python - Mouse clicks/Keyboard Clicks on window in background

I wanted to create a metin2 bot, nothing complicated. I am new into that so i just started to look for tutorials on youtube to find something that would lead me to world of coding, how does it work, what language is used to write it ect. So I found a tutorial on youtube about open CV Learn Code By Gaming - OpenCV and thought that's awesome thing to start with.
I got to the point where I can easily detect the names of monsters/metins and wont have any problems in finding the right points to click. After detection started working I thought about automating clicking on the window to farm some items etc. Simple things like clicking e.g 50 pixels below the name to auto attack worked just fine but the problem was that I wanted to make more bots to maximalize farming. So when i started to add more clients I got a problem where e.g you have to hold down SPACE in one window to attack from horse and click on another window which was stopping attacking from horse. So I thought about finding some code that can basically send message directly to window without controlling a mouse or keyboard so you can run multiple bots in one time and each will do perfect meanwhile you can do anything else on pc because your mouse and keyboard aren't used.
Let's start from code I found and none worked for windows in background (even with administrator privileges). Pyautogui doesn't work in background (window has to be in foreground to be clicked on and it controls mouse so there is no point in using that.
From that code I learned that I need to find "window ID" to connect to it and send messages. When i print hWnd it shows the numbers in Terminal and code passes without any fails but does nothing except printing the window ID ( Parent Handle ). Ofc I pip installed pywin32
import win32gui
import win32api
import win32con
def click(x, y):
hWnd = win32gui.FindWindow(None, "Client")
print(hWnd)
lParam = win32api.MAKELONG(x, y)
win32api.SendMessage(hWnd, win32con.WM_LBUTTONDOWN, win32con.MK_LBUTTON, lParam)
win32api.SendMessage(hWnd, win32con.WM_LBUTTONUP, win32con.MK_LBUTTON, lParam)
click(100, 100)
Than i found another code that looked similar but used different function so first i used
wdname = 'Client'
hwnd = win32gui.FindWindow(None, wdname) # parent handle
print(hwnd)
Which printed me a window ID that i used in parameters in function
def control_click(x, y, handle, button):
l_param = win32api.MAKELONG(x, y)
if button == 'left':
win32gui.PostMessage(handle, win32con.WM_LBUTTONDOWN, win32con.MK_LBUTTON, l_param)
win32gui.PostMessage(handle, win32con.WM_LBUTTONUP, win32con.MK_LBUTTON, l_param)
elif button == 'right':
win32gui.PostMessage(handle, win32con.WM_RBUTTONDOWN, 0, l_param)
win32gui.PostMessage(handle, win32con.WM_RBUTTONUP, 0, l_param)
control_click(200, 200, 329570, button ='left')
But it still did nothing but code passed clear
Anyone have any ideas about how to make clicks/keyboard clicks in python on window in background without taking controll of mouse/keyboard? If you have any experience in automating and know better ways to create automation for clicking ect. and want to share it please do. If that can be done in another programming language also share your toughts about that of course if you want to.
Windows 10 x64
Python used: 3.9.2
All codes i found in topics were out of date that s why i am asking for help there. Thanks in advance :)

pywinauto possible to keep application alive if I exit python script?

app = Application(backend="uia").start("program.exe")
I am using pywinauto to do some tasks indefinitely. However, occasionally, I need to restart the script for some external reasons. When this happens, I would like to keep the created applications open. How can I do this? I noticed if the python script errors out, the applications will stay open. But if I exit the script manually, the windows will close. So there must be some way to accomplish this.
I think pywinauto's Application.start cannot do the work. You can try:
pid = os.spawnl(os.P_NOWAIT, "program.exe")
app = Application().connect(process=pid)
os.spawnl is considered deprecated. Use subprocess module.
Combining the answer in Run a program from python, and have it continue to run after the script is killed and pywinauto official doc, you can do this:
subprocess.Popen(
['your_program', 'with args'],
# These will make sure the desktop program will alive even when shell session terminates.
creationflags=subprocess.DETACHED_PROCESS | subprocess.CREATE_NEW_PROCESS_GROUP, shell=True
)
desktop = Desktop(backend="uia")
main_win = desktop.window(title="program's window title", control_type="Window")
Why not use system command:
#Use multiple thread to avoid block of system function
import _thread as qd
import os
qd.start_new_thread(os.system,('notepad',))
from pywinauto import Application
#connect pywinauto with application via title regular expression
win=Application(backend='uia').connect(title_re='.*Notepad.*')
Then you use pywinauto to connect application via title?

How to configure tkinter buttons to seem more modern

Okay so I'm a teacher using tkinter to create gui's with my students. My mac users are fine with the look but in windows their programs leave something to be desired. I don't have access to PIP (my sys admin WONT open it up for the kids to use terminal) so I'm limited in my libraries.
Im (slowly) building up some configurations that i think would help them get the idea behind how to configure (I explain its like adding CSS to HTML - doens't (usually) change the function, it just looks better) any tips or examples i can pass on to them would be super helpful. Here is an example of a slider i turned into a tactile on/off switch.
import tkinter as tk
main = tk.Tk()
def on_off_slider_action(slider_val):
if int(slider_val): #using as "truthy"
on_off_slider.configure(troughcolor="#00FF00")
else:
on_off_slider.configure(troughcolor="#FF0000")
on_off_slider = tk.Scale(main, from_=0,
to=1,orient=tk.HORIZONTAL,length=50,showvalue=0,
command=on_off_slider_action,width=30)
on_off_slider.configure(bd=0)
on_off_slider.configure(relief=tk.FLAT)
on_off_slider.configure(sliderrelief=tk.FLAT)
on_off_slider.configure(bg="#999999", activebackground="#888888" )
on_off_slider.grid(row=0,column=0)
main.mainloop()
example switch off
example switch on

How can I introduce an embedded terminal with tkinter?

I am trying to make a simple GUI with some basic options of GPG in order to make it easier for new people to use this tool. I need to place a terminal in my GUI, so that trough the GUI the user can click buttons which activate commands in the terminal. With this program people could get used to see the commands working and I avoid the problem of the introduction of the passwords. I want this program to be free software, so that if anyone who helps wants to complete it and share it, please feel free to doing so (well, I would like to see it working correctly firstxD)
I have searched this things but the only answer which looked useful for me does not work (when I click the button of send it simlpy does nothing). I leave here the link to the this other question and my code:
Link: Giving a command in a embedded terminal
My code:
from tkinter import *
import tkinter.ttk as ttk
import os
def cifrado():
archivo=filebox.get()
algoritmo=algo_selec.get()
orden='gpg -ca --cipher-algo '+str(algoritmo)+' '+str(archivo)
os.system(orden) #I need to run this on the terminal
window=Tk()
window.title('GPG Gui')
window.geometry("600x600")
notebook=ttk.Notebook(window)
notebook.pack(fill='both', expand='yes')
frame1 = ttk.Frame(notebook)
frame2 = ttk.Frame(notebook)
notebook.add(frame1, text='Cifrados simétricos')
notebook.add(frame2, text='Cifrados asimétricos')
#Symmetric encryption part
filelabel=Label(frame1,text='Archivo: ')
filelabel.grid(row=1,column=1)
filebox=Entry(frame1)
filebox.grid(row=1,column=2)
algolabel=Label(frame1,text='Algoritmo: ')
algolabel.grid(row=2,column=1)
algo_selec=ttk.Combobox(frame1,values=["IDEA","3DES","CAST5","BLOWFISH","AES","AES192","AES256","TWOFISH","CAMELLIA128","CAMELLIA192","CAMELLIA256"]) #DESPLEGABLE
algo_selec.set("AES256")
algo_selec.configure(width=18)
algo_selec.grid(row=2,column=2)
keylabel=Label(frame1,text='Contraseña: ')
keylabel.grid(row=3,column=1)
keybox=Entry(frame1,show="*",width=20)
keybox.grid(row=3,column=2)
b1=Button(frame1,text="Cifrar",command=lambda:cifrado())
b1.grid(row=1,column=3)
#Well, I need to write here the code of the terminal and connect it to the 'cifrado()' function
#Asymmetric encryption
window.mainloop()

Resources