PyGTK: Allow only one instance of your application
In the post “Python: Allow only one instance of your application” I presented a method that works great for non GUI applications. It work’s fine for GUI applications too but if the application is already running the second instance will just quit. What if the application instance’s window is hidden by other window ?
In this case the best behavior is: if the GUI application is already running, the second application raise it and then quit. This provides a better user experience.
I read about gtk.gdk.Window.raise_() method. I don’t know why but it’s working (at least in my case) !!! The application’s window remains behind other windows.
The only working functions that I found, was:
- gtk.Window.present_with_time(): works all the time but it does not activate the window
- gtk.Window.present: it does not works all the time (ex: it does not works if the application shows a modal dialog on the main window), but when it does it activate the window too
The best way is to call them both. In the worst case the window is raised but is not activate.
The problem with this functions is that it must be called in the application instance, because I didn’t find a way to create a gtk.Window for an external xid (only gtk.gdk.Window). So when the second application starts it must inform the “only” application instance to raise it’s window.
There are different methods to comunicate between applications and I will not discuss them here. A simple and “lazy” solution is to create a file. The application instance will check from time to time if the file exists. If the file exists raise it’s window. We can can write some information in this file so that the application instance can use it.
This is my “Hello World !” application instance: gtkapplicationinstance.py. This application checks every second if it needs to raise itself.
<br /> <b>Warning</b>: include(/home2/macadanc/public_html/le-web.org/wp-content/uploads/2008/11/gtkapplicationinstance.py) [<a href='function.include'>function.include</a>]: failed to open stream: No such file or directory in <b>/home2/macadanc/public_html/le-web.org/wp-content/plugins/include-it/plugin.php</b> on line <b>86</b><br /> <br /> <b>Warning</b>: include() [<a href='function.include'>function.include</a>]: Failed opening '/home2/macadanc/public_html/le-web.org/wp-content/uploads/2008/11/gtkapplicationinstance.py' for inclusion (include_path='.:/usr/share/pear:/usr/share/php') in <b>/home2/macadanc/public_html/le-web.org/wp-content/plugins/include-it/plugin.php</b> on line <b>86</b><br />