How to catch CTRL+C

In my previous post, I was talking about this annoyance on catching the interruption triggered by CTRL+C.

It turned out, as I suggested, that I found a work around to this issue. As I searched, I realized that it is also not a trivial thing to do in C++. It seems to be highly plateform dependent.

I have the feeling that Mathworks introduced OnCleanup expecially to deal with these issues. In contrary to TRY/CATCH, On cleanup does catch CTRL-C. The purpose of this function seems to be different though. TRY/CATCH is to deal with errors. OnCleanup is to help you cleanup your workspace in all situation (in normal operation and after errors). The advantage of such a scheme is that you don’t have to write down these clean-up operations 2 times (ie in your catch AND in your try). Let’s suppose you want to use the code I proposed to pause your GUI during calculation. Now instead of this :

% We turn the interface off for processing.
InterfaceObj=findobj(HandleToFigWindow,'Enable','on');
set(InterfaceObj,'Enable','off');

%%%%%%%%%%%%%%%%%%%%%%%%%%%
%                         %
%   PUT YOUR CODE HERE    %
%                         %
%%%%%%%%%%%%%%%%%%%%%%%%%%%

% We turn back on the interface
set(InterfaceObj,'Enable','on');

I remind you that HandleToFigWindow is the handle to your GUI interface.

With onCleanup, You would do this :

% We turn the interface off for processing.
InterfaceObj=findobj(HandleToFigWindow,'Enable','on');

% We turn it back on in the end
Cleanup1=onCleanup(@()set(InterfaceObj,'Enable','on'));

%%%%%%%%%%%%%%%%%%%%%%%%%%%
%                         %
%   PUT YOUR CODE HERE    %
%                         %
%%%%%%%%%%%%%%%%%%%%%%%%%%%

This look very similar, except that the second version will ensure that you interface is back on even if a CTRL+C has been sent by your GUI user. Notice how I removed the set in the end.

This entry was posted in Advanced, Annoyances, Intermediate. Bookmark the permalink.

Leave a Reply