Skip to content Skip to sidebar Skip to footer

How Can I Make My Pyqt5 App Oney One Instance?

What I want to achieve: when I run application from start menu, app starts (if app not running). If an app is already running, then don't create another instance, just show the pr

Solution 1:

You can achieve something similar with the win32gui module. To install it type into CMD pip install pywin32. Now this is the code:

from win32 import win32gui
import sys

defwindowEnumerationHandler(hwnd, top_windows):
    top_windows.append((hwnd, win32gui.GetWindowText(hwnd)))

top_windows = []
win32gui.EnumWindows(windowEnumerationHandler, top_windows)
for i in top_windows:
    if"Program"in i[1]: #CHANGE PROGRAM TO THE NAME OF YOUR WINDOW
        win32gui.ShowWindow(i[0],5)
        win32gui.SetForegroundWindow(i[0])
        sys.exit()


from PyQt5.QtWidgets import QApplication, QWidget

defmain():

    #YOUR PROGRAM GOES HERE

    app = QApplication(sys.argv)

    w = QWidget()
    w.setGeometry(500, 500, 500, 500)
    w.setWindowTitle('Simple')
    w.show()

    sys.exit(app.exec_())


if __name__ == '__main__':
    main()

Basically, at the beginning, the program gets the name of every open window. If the window name is equal to the name of the program, then it brings the program to the front and closes the program. If not, then it opens a new program.

PyWin32 link

Stack Overflow get a list of every open window

Post a Comment for "How Can I Make My Pyqt5 App Oney One Instance?"