How to prevent Pynput when the application is in background in Python

Question:

I’m trying to prevent the pynput framework when my GUI is in background. I’m using pynput to make shortcuts for some buttons. I use PyQT5 for GUI.

from pytube import YouTube
from PyQt5 import QtCore, QtGui, QtWidgets
from tkinter.messagebox import showerror as hata, showinfo as bilgi, showwarning as uyari, askyesno as soru
from sys import argv, exit as exiting
from threading import Thread as th
from GUI import *
from numpy import arange as range
import sqlite3 as sql
import youtube_dl
import vlc
import time
import os
from pynput.keyboard import Listener
from keyboard import is_pressed as pressed, press


def Listener(self):
        def Listener_thread():
            with Listener(on_press=self.onpress) as listener:
                press("X")
                listener.join()
        t1 = th(target=Listener_thread)
        t1.start()


    def onpress(self, key):
        if pressed("ESC"):
            os.system(fr"taskkill /f /im {__file__.split(chr(92))[-1]}")
            
Asked By: Deezwend

||

Answers:

You use the pressed function from the keyboard module that listen to keys even if you do not focus the window.

so you have to use the hasFocus() or self.isActiveWindow() function from the PYQT5 module

Syntex

if pressed("ESC") and self.hasFocus():
            os.system(fr"taskkill /f /im {__file__.split(chr(92))[-1]}")

# or 

if pressed("ESC") and self.isActiveWindow():
            os.system(fr"taskkill /f /im {__file__.split(chr(92))[-1]}")
Answered By: codester_09
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.