Search code examples
pythonpynput

Python argument to select a specific window


I'm trying to code a Discord bot, that when you type !start it starts a process on my computer and when you type !stop it stops the server, but here's the deal, when you type the command !stop it doesn't write my code in a cmd but wherever your cursor is selected to write.

This is very complicated to explain but in summary I just want to know if there is a specific argument that can change which window is selected.

I'm a newbie to python, so please explain in detail. I'm using pynput to have the ability to have control of my keyboard to stop my server.

Here's the code, I just need to be able to execute this only in a cmd even if I'm in chrome.

import os
import time
from pynput.keyboard import Key,Controller

keyboard = Controller()


time.sleep(10)
keyboard.type("stop")
keyboard.press(Key.enter)
keyboard.release(Key.enter)

time.sleep(10)

keyboard.type("a")
time.sleep(10)

keyboard.type("exit")
keyboard.press(Key.enter)
keyboard.release(Key.enter)

Solution

  • If your operating system is Windows, you can use PyGetWindow to switch windows.

    import pygetwindow as gw
    
    print(gw.getAllTitles())
    handle = gw.getWindowsWithTitle('Notepad')[0]
    handle.activate()
    handle.maximize()