import time import ctypes from pynput.keyboard import Key from pynput.keyboard import Controller a=0 while True: if ctypes.windll.user32.GetForegroundWindow() == 0: print('0') time.sleep(2) else: a = a+1 b = Controller() b.press(Key.f20) b.release(Key.f20) time.sleep(30) print('1') print(a)