How do I run a function when a user of my app closes it?

My app activates manual proxy settings when a connection toggle is turned on and turns proxy off when toggle position is reversed. The problem is, if a user presses a cross to shut the app down, they are left with manual proxy mode and broken internet.

My current code, where I already tried some solutions I found online:

class App(Adw.Application):
    def __init__(self):
        super().__init__(application_id="com.example.VPNApp")
        self.connect("shutdown", self.on_shutdown)

    def do_activate(self):
        # Create and show the main app window
        global window
        window = EvadeWindow(application=self)
        window.present()
        app.inhibit(win, Gtk.ApplicationInhibitFlags.LOGOUT |
        Gtk.ApplicationInhibitFlags.SUSPEND, 'It\'s time to do some tasks:\n1) Task one ...\n2) Task two ...\n3) Task three ...')

    def on_shutdown(self, app):
        shut_sing_box_processes()
        print('all sb shdown')

None of them work. It should print 'all sb shdown' every time I press an X, but I’m left with broken proxy instead.

The X is closing a window? If so catch the windows close event maybe?

You can connect to the window’s close-request signal:

Is there a manual on how to do it with PyGObject?

https://lazka.github.io/pgi-docs/#Gtk-4.0/classes/Window.html#Gtk.Window.signals.close_request

Here’s a random example:

Okay, that works. Turns out I was inserting all my solutions to window.py instead of main.py that had the same classes.

I avoid doing that in my code so that I do not confuse myself.