cocos2d mobile phone exit and menu button response

Example for cocos2d-3.9
using HelloWorldScene.h and HelloWorldScene.cpp

#ifndef __HELLOWORLD_SCENE_H__
#define __HELLOWORLD_SCENE_H__

#include "cocos2d.h"
//Note this, look for this file and import the cpp file in the cocos2d-x-3.9\tests\cpp-tests\Classes directory
#include "VisibleRect.h"

class HelloWorld : public cocos2d::Layer
{
public:
    static cocos2d::Scene* createScene();

    virtual bool init();
    
    // a selector callback
    void menuCloseCallback(cocos2d::Ref* pSender);
    
	//Add this method to handle key events  
	void onKeyReleased(EventKeyboard::KeyCode keyCode, Event* event);

    // implement the "static create()" method manually
    CREATE_FUNC(HelloWorld);
};

#endif // __HELLOWORLD_SCENE_H__



....
//Add key monitoring (the following 3 lines are placed in the init method, and when they are placed in createScene, an error will be reported, but I didn't read the details)
auto listener = EventListenerKeyboard::create();
listener->onKeyReleased = CC_CALLBACK_2(HelloWorld::onKeyReleased, this);
_eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this);
....


//The following method can be placed at the end of the file
//Key control (detect onKeyReleased response)
void HelloWorld::onKeyReleased(EventKeyboard::KeyCode keyCode, Event* event)
{
	switch(keyCode)
	{
		//listen for return key
	case EventKeyboard::KeyCode::KEY_ESCAPE:              
		Director::getInstance()->end();  
		break;
		//Listen to the menu key
	case EventKeyboard::KeyCode::KEY_MENU:      
		break;
	}
}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=327079063&siteId=291194637