Make changes from one instance of application in other instance

92 Views Asked by At

➤ What I want: I have a window & a label in that window, when app is ran for the first time, label shows default text, but if user tries to launch second space, second space doesn't launch, instead it changes the label in the first instance which was already running

➤ Problem I'm facing: I stopped the second instance from running, with help, successfully, but I couldn't understand how to change the label in first instance.

➤ Minimal Reproducible code:

import sys
from PyQt5.QtWidgets import *
from win32 import win32gui


class Window(QMainWindow):

    def __init__(self) -> None:
        super().__init__()
        self.setWindowTitle('My Program')
        self.resize(400, 400)
        self.set_label()
    
    def set_label(self, text='This is an example'):
        self.lab = QLabel(self)
        self.lab.move(50, 50)
        self.lab.setText(text)


if __name__ == "__main__":
    
    # Check if app is already running & Close the app
    def windowEnumerationHandler(hwnd, top_windows):
        top_windows.append((hwnd, win32gui.GetWindowText(hwnd)))
    top_windows = []
    win32gui.EnumWindows(windowEnumerationHandler, top_windows)
    for i in top_windows:
        if i[1] == 'My Program':
            print('App is already running')
            
            # I know below line is wrong [tha's why commented out]
            # Window.set_label('Success')       # How to achieve it
            ## I want the label text to be changed in the already running instance
            
            sys.exit()    # Exit app (second instance)
    
    
    # Starting Application
    app = QApplication(sys.argv)
    win = Window()
    win.show()
    app.exec()
0

There are 0 best solutions below