Shumkar has asked for the wisdom of the Perl Monks concerning the following question:

Hi,

I'm wondering, is it possible to catch exiting Perl/Tk program when the user pushes "Exit" button on the top-right corner?

I have provided the Menu feature "File->Exit" which performs all necessary saving procedures but nothing prevents the user from (casual) pushing "Exit" button on the top-right corner, and in this case results of the user's work may be incorrect/lost.

If not possible - may be, is there any way to toggle "Exit" button from the top-right corner of the Perl/Tk MainWindow?

All questions - about WinXP.

  • Comment on How to catch pushing the window "Exit" button in Perl/Tk?

Replies are listed 'Best First'.
Re: How to catch pushing the window "Exit" button in Perl/Tk?
by zentara (Cardinal) on Aug 18, 2010 at 12:41 UTC
    I'm not sure if this works on Windows, but on Linux, this disables or intercepts the window manager's close button. If you just want to disable the close icon, set the sub to an empty {}.
    #!/usr/bin/perl use warnings; use strict; use Tk; my $mw = new MainWindow; $mw->title("Close test"); $mw->geometry("400x250"); #prevents mw from closing $mw->protocol('WM_DELETE_WINDOW' => sub { print "do stuff here before the exit\n"; exit; }); MainLoop;

    I'm not really a human, but I play one on earth.
    Old Perl Programmer Haiku
Re: How to catch pushing the window "Exit" button in Perl/Tk?
by thundergnat (Deacon) on Aug 18, 2010 at 12:56 UTC

    Trap the window manager exit signal and redirect to your own exit routine. Cross platform. This won't trap someone closing or entering ctrl-c in the command.exe window. The best way to defend against that is to use wperl. (under windows)

    Oops. zentara posted the correct answer while I was typing. Anyway; me too!

    use warnings; use strict; use Tk; use Tk::DialogBox; my $mw = MainWindow->new; $mw->protocol('WM_DELETE_WINDOW' => \&myexit); MainLoop; sub myexit{ my $db = $mw->DialogBox(-title => "Are you sure you want to exit?" +, -buttons => ['OK', 'Cancel']); my $answer = $db->Show; Tk::exit if $answer eq 'OK'; }

      >I'm not sure if this works on Windows, but on Linux, this disables or intercepts the window manager's close button.
      >$mw->protocol('WM_DELETE_WINDOW' => sub {

      >$mw->protocol('WM_DELETE_WINDOW' => \&myexit);

      WoW! It does work on Windows too! Thanks a lot, guys!