Introduction

Matlab Logo This tutorial will show you how to create a confirmation window when you attempt to close the GUI. Sometimes, the user might accidentally close the GUI window without meaning to. To protect against this, we can implement a confirmation window that appears when the user attempts to close the GUI. This feature can protect the user from losing any work that has been performed.

close confirmation window

This tutorial is written for those with some experience creating a Matlab GUI. If you’re new to creating GUIs in Matlab, you should visit this tutorial first. Basic knowledge of Matlab is highly recommended. Matlab version 2007a is used in writing this tutorial. Both earlier versions and new versions should be compatible as well (as long as it isan’t too outdated). Let’s get started!

Creating the Confirmation Window: Method 1

  1. First, you need to add the following line of code to the opening function of your GUI.
    set(handles.figure1,'CloseRequestFcn',@closeGUI);

    This line is of code is telling matlab to run the closeGUI function once someone attempts to close the GUI figure. Make sure to put this line of code before the line

    guidata(hObject, handles);
  2. Next, copy this code at the end of the GUI .m file OR in a separate .m file, but make sure it’s saved in the same directory where the GUI files are located.

    function closeGUI(src,evnt)
    %src is the handle of the object generating the callback (the source of the event)
    %evnt is the The event data structure (can be empty for some callbacks)
    selection = questdlg('Do you want to close the GUI?',...
                         'Close Request Function',...
                         'Yes','No','Yes');
    switch selection,
       case 'Yes',
        delete(gcf)
       case 'No'
         return
    end

Creating the Confirmation Window: Method 2

  1. First, you need to add the following line of code to the opening function of your GUI.
    set(handles.figure1,'CloseRequestFcn','closeGUI');

    Notice that instead of the @, we use the single quotation marks. By using the single quotation marks, you are assigning a separate m-file to the close request function of the figure. Make sure to put this line of code before the line

    guidata(hObject, handles);
  2. Next, copy this code into a separate .m file, but make sure it’s saved in the same directory where the GUI files are located. Notice that we did not define any input arguments here.

    function closeGUI
     
    selection = questdlg('Do you want to close the GUI?',...
                         'Close Request Function',...
                         'Yes','No','Yes');
    switch selection,
       case 'Yes',
        delete(gcf)
       case 'No'
         return
    end

And that’s it!!! Pretty simple like I mentioned. If you want to see an example, go ahead to the next page.

Pages: 1 2