将字符转换为键盘码的代码

以下这段代码可以将字符串转换为键盘码,以备需要时用到。


- (int)keyCodeForCharacter: (NSString*)character {
  if(![character length]) return -1;

 char code;
  BOOL shift, alt;
 if(Ascii2Virtual( (char)[character characterAtIndex: 0], &shift, &alt, &code)) {
return code;
}
  return -1;
}


BOOL Ascii2Virtual(char pcar, BOOL *pshift, BOOL *palt, char *pkeycode)
{
    KeyboardLayoutRef keyboard;
    const void *keyboardData; // keyboard layout data
    UInt16 nbblocs;
    char *modblocs, *blocs, *deadkeys;
    int ix, ifin, numbloc, keycode;
   
    BOOL shift, alt;
    // get the current keyboard
    if(KLGetCurrentKeyboardLayout(&keyboard)) return NO;
    // get the description of the current keyboard layout
    if(KLGetKeyboardLayoutProperty(keyboard, kKLKCHRData, &keyboardData)) return NO;
    // get pointer early numbers of blocks for each combination of modifiers
    modblocs = ((char *)keyboardData) + 2;
    // get number of blocks keycode->ascii
    nbblocs = *((UInt16 *)(keyboardData + 258));
    // get pointer early blocks keycode-> ascii
    blocs = ((char *)keyboardData) + 260;
    // determining the size of all tables keycode-> ascii a scanner
    ifin = nbblocs*128;
    // determining pointer early in the tables of dead keys
    deadkeys = blocs+ifin;
    // Now it runs blocks keycode-> ascii to find the car ascii
    for (ix=0; ix<ifin ; ix++)
    {
        if (blocs[ix]==pcar)
        {
 
            // found ascii value: now we must determine which block it is
            keycode = ix & 0×7f; // 0111 1111 mask
            numbloc = ix >> 7;
            break;
        }
    }
 
    // not found: bail out (error)
    if (ix >= ifin) return NO;
 
    // from block number, we must find the combination of modifiers using this block
    for (ix=0; ix<15; ix++)
    {
        // it does not address whether the modifiers are not "capital" and "option"
        if (ix&1 || ix&4) continue;
        // Combining modifiers found for the block
        if (modblocs[ix]==numbloc)
        {
            shift = (ix&2) ? YES : NO;
            alt   = (ix&8) ? YES : NO;
            break;        
        }
    }
    // combination modifiers not found: bail
    if (ix>=15) return NO;
    // save our parameters
    *pkeycode=keycode;
    *pshift=shift;
    *palt=alt;
   
    return YES;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值