原文地址: http://www.vktone.com/articles/win32_key_process_in_cocos2dx.html
首先在AppDelegate.cpp加入以下代码,一定要在AppDelegate::applicationDidFinishLaunching()上,声明用的。
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32)
HelloWorld *g_layer;void Win32SetKeyLayer(HelloWorld *layer)
{g_layer = layer;
}void Win32KeyHook( UINT message,WPARAM wParam, LPARAM lParam )
{CCLog("Win32KeyHook message %d wParam %d lParam %d", message, wParam, lParam);if (g_layer)g_layer->onWin32KeyEvent(message, wParam, lParam);
}
#endif
在AppDelegate::applicationDidFinishLaunching()中
bool AppDelegate::applicationDidFinishLaunching() {// initialize directorCCDirector* pDirector = CCDirector::sharedDirector();CCEGLView* pEGLView = CCEGLView::sharedOpenGLView();#if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32)// 2012.11.07 加入键盘处理代码pEGLView->setAccelerometerKeyHook(Win32KeyHook);///
#endif // CC_PLATFORM_WIN32pDirector->setOpenGLView(pEGLView);// turn on display FPSpDirector->setDisplayStats(true);// set FPS. the default value is 1.0/60 if you don't call thispDirector->setAnimationInterval(1.0 / 60);// create a scene. it's an autorelease objectCCScene *pScene = HelloWorld::scene();// runpDirector->runWithScene(pScene);return true;
}
在HelloWorldScene.cpp中
CCScene* HelloWorld::scene()
{// 'scene' is an autorelease objectCCScene *scene = CCScene::create();// 'layer' is an autorelease objectHelloWorld *layer = HelloWorld::create();// add layer as a child to scenescene->addChild(layer);extern void Win32SetKeyLayer(HelloWorld *layer);Win32SetKeyLayer(layer);// return the scenereturn scene;
}
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32)
void HelloWorld::onWin32KeyEvent( UINT message,WPARAM wParam, LPARAM lParam )
{CCLog("onWin32KeyEvent message %d wParam %d lParam %d", message, wParam, lParam);/*// UpWin32KeyHook message 256 wParam 38 lParam 21495809onWin32KeyEvent message 256 wParam 38 lParam 21495809Win32KeyHook message 257 wParam 38 lParam -1052246015onWin32KeyEvent message 257 wParam 38 lParam -1052246015// DownWin32KeyHook message 256 wParam 40 lParam 22020097onWin32KeyEvent message 256 wParam 40 lParam 22020097Win32KeyHook message 257 wParam 40 lParam -1051721727onWin32KeyEvent message 257 wParam 40 lParam -1051721727// LeftWin32KeyHook message 256 wParam 37 lParam 21692417onWin32KeyEvent message 256 wParam 37 lParam 21692417Win32KeyHook message 257 wParam 37 lParam -1052049407onWin32KeyEvent message 257 wParam 37 lParam -1052049407// RightWin32KeyHook message 256 wParam 39 lParam 21823489onWin32KeyEvent message 256 wParam 39 lParam 21823489Win32KeyHook message 257 wParam 39 lParam -1051918335onWin32KeyEvent message 257 wParam 39 lParam -1051918335*/if (message == 256){switch (wParam){case 38:moveHero(1);break;case 40:moveHero(2);break;case 37:moveHero(3);break;case 39:moveHero(4);break;}}else if (message == 257){}
}
#endif
void HelloWorld::moveHero( int diraction )
{CCLog("moveHero: %d",diraction);
}
//现在你就可以上下左右键,看输出的值。