Detect a long press mouse click

In my project I’d like to do some stuff after 5 seconds that I keep pressed my mouse from the mouseDown, how can I do?

Thank you!

juce::MouseEvent::getLengthOfMousePress

2 Likes

make a class that inherits from juce::Component, then implement the virtual method mouseDown() to start a timer and let mouseUp() stop the timer. in the timerCallback() method you get the current time between calls via std::chrono (check out the cherno’s c++ tutorials. he has an episode about that). and you add all these values together. if they exceed a certain time (5 sec) you stop the timer and trigger your special method that does the thing. (this is the long version of the method suggested above. this has the advantage that your code only does certain things, when a mouseDown is currently happening and else does nothing, which might be resource-friendly depending on what you do with that info)

2 Likes

Normally you want the action to take place when the predefined timer expires, not after the mouse has been released, so a possible implementation would be a sort of “one-shot timer”:

class myComponent : juce::Timer 
{
	//...
	
	void mouseDown(const MouseEvent& e) override
	{
		startTimer(1000);
	}
	
	void mouseUp(const MouseEvent& e) override
	{
		stopTimer(); // Make sure the timer is stopped even if the timeout is not reached
	}

	void timerCallback() override
	{
		stopTimer();
		
		// ... Do something "on long press"...

	}
};