Detect KeyDown and KeyUp


#1

Hello,

I’m wondering if there is a simple way to detect a specific key keyDown (or press) and a keyUp (or release) event ?
For now I’ve inherited from the KeyListener class and implemented keyPressed and keyStateChanged but I’m wondering if there is a easier way of getting those specific events. Because in the keyPressed I think I cannot have access the down or up information and in the keyStateChanged I think I cannot have access to the keycode.

Thank you in advance


#2

Most apps will only be interested in getting events for a particular key. In this case you override the keyStateChanged method and use KeyPress::isKeyCurrentlyDown() to check if that particular key is up or down.

If you really need to have up/down events for all keys then it’s best to override keyPressed with something that stores a copy of the KeyPress object in some kind of set, and keyStateChanged should then query all the keys in the set - removing them from the set if they are not down anymore.


#3

Thank you for your answer.

That’s exactly what I want.
The main issue I have is that I cannot catch when the particular key has been released:

bool CanvasView::keyStateChanged(bool isKeyDown, Component * originatingComponent)
{
	if (isKeyDown)
	{
		if (KeyPress::isKeyCurrentlyDown(KeyPress::spaceKey))
		{
			DBG("SPACE DOWN");
		}
	}
	else 
	{
             
		if (KeyPress::isKeyCurrentlyDown(KeyPress::spaceKey))
		{
			DBG("SPACE UP"); // never called
		}
	}

	return false;
}

#4

You need to invert the second if (KeyPress::isKeyCurrentlyDown(KeyPress::spaceKey)):

bool CanvasView::keyStateChanged(bool isKeyDown, Component * originatingComponent)
{
	if (isKeyDown)
	{
		if (KeyPress::isKeyCurrentlyDown(KeyPress::spaceKey))
		{
			DBG("SPACE DOWN");
		}
	}
	else 
	{
		 // Don't print "SPACE UP" if some other key went up, so check that it's the space key which actually went up
		if (! KeyPress::isKeyCurrentlyDown(KeyPress::spaceKey))
		{
			DBG("SPACE UP"); // never called
		}
	}

	return false;
}

Even better is the following:

bool CanvasView::keyStateChanged(bool isKeyDown, Component * originatingComponent)
{
    // it's better if this is a member variable. Using static just for this example here:
	static auto lastSpaceKeyIsDown = false;
	
	auto newSpaceKeyIsDown = KeyPress::isKeyCurrentlyDown(KeyPress::spaceKey);
	
	if (newSpaceKeyIsDown != lastSpaceKeyIsDown)
	{
		lastSpaceKeyIsDown = newSpaceKeyIsDown;
		
		if (newSpaceKeyIsDown) DBG ("Space DOWN");
		else                   DBG ("Space UP");
	}
}

#5

Oh yes my bad, I was confused, thank you very much !