Detection of Ctrl+C in M file

82 次查看(过去 30 天)
Hi everyone
I want to detect when somebody press "Ctrl C". How can I be detected it while an function is be running . if I do that , I will save some of variables to workspace.

采纳的回答

Geoff Hayes
Geoff Hayes 2014-9-30
Ilkay - you can try the following which is taken from Loren Shure's blog entry Keeping Things Tidy. It makes use of the onCleanup function which will perform "cleanup" tasks upon function completion or termination.
Suppose you have some function that does some work in a while or for loop which may take so long that the user becomes impatient and presses the ctrl+c to cancel out of the function. Within that function, we define a clean up function to fire when our main function/program terminates
function someFunction
% create our clean up object
cleanupObj = onCleanup(@cleanMeUp);
% load an image, create some variables
I = imread('someImage.jpg');
Z = zeros(42,24,42);
U = ones(1,2,3);
keepGoing = true;
while keepGoing
% do our work
% add a 100 msec pause
pause(0.01);
end
% fires when main function terminates
function cleanMeUp()
% saves data to file (or could save to workspace)
fprintf('saving variables to file...\n');
filename = [datestr(now,'yyyy-mm-dd_HHMMSS') '.mat'];
save(filename,'I','Z','U');
end
end
I tried the above on MATLAB R2014a (Mac OS X 10.8.5) and it would respond to the pressing of ctrl+c - firing the cleanMeUp function before terminating. Of course, that same function will fire if the program terminates regularly (i.e. if some exit condition is met and the code exits the while loop gracefully).
  1 个评论
felipe masetti
felipe masetti 2022-6-30
If your app is running on continuous loop and the work is not inside the while loop, bein triggered by events or timers for example, consider using "waitfor(keepGoing)", it will use less resources just to wait than the loop with pause.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

产品

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by