zu www.bildungsgueter.de next page Table of Section Contents previous page

Asking Permission Before a Window is Closed


Occasionally it is useful not to close a window immediately but to ask the user to confirm the close request. To do that, you have to provide a handler for the deleteEvent of your window. That handler is required to have the type

Window ->  IO Bool

The return value of that handler indicates whether or not the user allows to close the window.

The handler itself opens a dialog window to obtain a decision.

Archive file with this example: Example003.tar.gz. Be sure to read the file README.txt for further instructions.

import "gtk3" Graphics.UI.Gtk
import "gtk3" Graphics.UI.Gtk.Gdk.Events
import Control.Monad.IO.Class      -- for liftIO


deleteEventHandler :: Window ->  IO Bool
deleteEventHandler transientParentWindow =
    do
    dialog <- messageDialogNew (Just transientParentWindow)
                      [DialogDestroyWithParent] 
                      MessageQuestion 
                      ButtonsYesNo 
                      "Do you want to close this window ?"
    set dialog [windowTitle := "About to close"]
    result <- dialogRun dialog
    widgetDestroy dialog
    if result == ResponseYes
       then return False
       else return True


destroyEventHandler :: IO ()
destroyEventHandler =
  do mainQuit
  
main :: IO ()
main = do
    initGUI
    window <- windowNew
    set window [windowDefaultWidth := 250, windowDefaultHeight := 280,
                windowTitle := "Example 3"]
    on window deleteEvent $ liftIO (deleteEventHandler window)
    on window objectDestroy $ destroyEventHandler
    widgetShow window
    mainGUI

It is possible to write the event handler for the deleteEvent in a slightly different manner:

deleteEventHandler :: Window ->  IO Bool
deleteEventHandler transientParentWindow =
    do
    dialog <- messageDialogNew (Just transientParentWindow)
                      [DialogDestroyWithParent] 
                      MessageQuestion 
                      ButtonsYesNo 
                      "Do you want to close this window ?"
    set dialog [windowTitle := "About to close"]
    result <- dialogRun dialog
    widgetDestroy dialog
    let answer = result == ResponseNo
    return answer

previous page Table of Section Contents next page