您的位置:首页 > 其它

如何使后台运行的程序获取按键事件

2010-12-12 20:33 375 查看
一、基本思路: 

首先程序运行时注册按键事件,然后将程序转入后台运行,当按键事件发生后在AppUi的HandleKeyEventL中处理。 

相关代码如下: 

void CClockSSAppUi::SetCaptureKey() 

    // If there is another handle, we have to cancel it first. 
    CancelCaptureKey(); 
    // This will capture scan code of the keypress. 
    iHandleCaptureKey = CCoeEnv::Static()-> RootWin().CaptureKeyUpAndDowns( 
      KOkKeyScanCode, EModifierShift, EModifierShift PRIORITYCAPTUREKEY); 

    //// WARNING: We need to capture the normal code of keypress otherwise 
    // the key event will be sent to another application. 
    iHandleCaptureKey2 = CCoeEnv::Static()-> RootWin().CaptureKey( 
      KOkKeyCode, EModifierShift, EModifierShift PRIORITYCAPTUREKEY); 


TKeyResponse CClockSSAppUi::HandleKeyEventL(const TKeyEvent& aKeyEvent,TEventCode aType) 

if ((KOkKeyScanCode == (TUint) aKeyEvent.iScanCode) && (EEventKeyDown == aType) 
          && ((aKeyEvent.iModifiers & EModifierShift) == EModifierShift) ) 
          { 
          CAknGlobalNote* globalNote = CAknGlobalNote::NewLC(); 
          globalNote->ShowNoteL(EAknGlobalInformationNote, _L(”Captured KEY!”)); 
          CleanupStack::PopAndDestroy(); 
          } 


需要注意的是:如果你的是多view程序,并且调用了AppUi::AddToStackL接收按键事件,那么在这些控件OfferKeyEventL的处理中对于不相关的键事件一定要返回EKeyWasNotConsumed,好让AppUi最后能处理。 

二、如何将程序送到后台运行 

比如说,当按下back后,在HandleCommandL()中加入如下处理: 
case EAknSoftkeyBack: 
            { 
            TApaTask apaTask(iEikonEnv->WsSession()); 
            apaTask.SetWgId(CCoeEnv::Static()->RootWin().Identifier()); 
            apaTask.SendToBackground(); 
            break; 
            } 

解释一下: 
A task is a running application. 
A task is identified by its association with the running application’s window group. 
apaTask把自己送到后台,并在后台继续运行。 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: