필터 지우기
필터 지우기

Detection of Ctrl+C in M file

조회 수: 82 (최근 30일)
Ilkay Meseli
Ilkay Meseli 2014년 9월 30일
댓글: felipe masetti 2022년 6월 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