pythonwindowspycharmkeyboard-eventspyautogui

Python how to make the code work in one program and not in others


I am learning Python, I wrote the code for afk farm (minecraft). And I want to collapse the tab (minecraft) and watch YouTube there, or play another game so that the code continues to work in minecraft, but does not work in other programs, how to do this, thank you!

import pyautogui as ptg
import keyboard as key

isclicking = False

def check_clicking():
  global isclicking
if isclicking == True:
    isclicking = False
else:
    isclicking = True
key.add_hotkey('F10', check_clicking)

while True:
  if isclicking == True:
    ptg.doubleClick()

Solution

    1. Identify the program window
    2. Check the active window
    3. Continue clicking only the program

    First install pygetwindow:

    pip install pygetwindow

    Here's the implementation:

    import pyautogui as ptg
    import keyboard as key
    import pygetwindow as gw
    import time
    isclicking = False
    def check_clicking():
        global isclicking
        isclicking = not isclicking
    key.add_hotkey('F10', check_clicking)
    def is_minecraft_active():
        try:
            return 'Minecraft' in gw.getActiveWindow().title
        except AttributeError:
            return False
    while True:
        if  isclicking and is_minecraft_active():
            ptg.doubleClick()
            time.sleep(0.1)
        time.sleep(0.01)