How to count how many times a button was pressed?

10 次查看(过去 30 天)
I want to write a code where I can check how many times a button was pressed (keyboard, mouse or even a pointer).
The code I have now is not working the way I want. As I click on a button for more than 1 second, it gives me a counting of 10 or more times. I want my code to count the number of clicks someone does on a button despite they spent 1second or 5seconds with the finger pressed against the button. Here is my function:
function youPressedSpaceBrah
set(figure,'KeyPressFcn',@youPressedSomething,'Name','Multitasking Game - Alerta Visual Nivel 1','NumberTitle','off', 'MenuBar', 'none','ToolBar', 'none');
clf;
%State variables
count = 0;
allowCounting = true;
%Callback functions
%When the user presses a key
function youPressedSomething(~,eventdata)
if strcmp(eventdata.Character,' ')
if allowCounting
count = count+1
end
end
end
end
Here is the code to call my function to the main code:
function youPressedSomething(~,eventdata)
erros=erros+1;
end
Thanks for your support!

采纳的回答

PG_Dev
PG_Dev 2017-11-20
编辑:PG_Dev 2017-11-22
Joana,
If I understand your question correctly, you want to consider 'Press and Hold' of any key as a single key press. But usually press and hold of a key is considered as multiple quick key press-releases of the same key. So as you can see in the below code I've used a simple tic-toc combination to check if the time between a key press-release of the same key is less than 0.05s(you can tune this time if you want), in which case I'm just printing the key count value at that point without any increment.
function KeyPressAnalyze
KeyPress_Main = figure;
set(KeyPress_Main, 'KeyPressFcn',@KeyPress_Main_KeyPress_Callback, 'KeyReleaseFcn',@KeyPress_Main_KeyRelease_Callback);
KeyPressCount = 0;
PressedKeyCurrent = {};
function KeyPress_Main_KeyPress_Callback(Handle, Event)
tic;
PressedKeyCurrent = Event.Key;
end
function KeyPress_Main_KeyRelease_Callback(Handle, Event)
KeyReleaseTime = toc;
disp(KeyReleaseTime);
ReleasedKey = Event.Key;
if (strcmp(PressedKeyCurrent, ReleasedKey) && (KeyReleaseTime < 0.05))
disp(KeyPressCount);
else
KeyPressCount = KeyPressCount + 1;
disp(KeyPressCount);
end
end
end
Please let me know if this fixed your issue.
Regards
PG

更多回答(1 个)

Joana Alves
Joana Alves 2017-11-22
Hi PG_Dev,
yes, that did the trick on my problem! I can modify the press-release time so it's Ok! Thank You!

类别

Help CenterFile Exchange 中查找有关 Desktop 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by