2011-08-13 28 views
0

我有一個DWORD變量&我想測試是否在其中設置了特定位。我有我的代碼在下面,但我不知道如果我正確地從win32數據類型KBDLLHOOKSTRUCT傳輸到我的lparam數據類型?測試是否在DWORD標誌中設置了特定位

請參閱MSDN,其中記錄的DWORD標誌變量:http://msdn.microsoft.com/en-us/library/ms644967(v=vs.85).aspx

union KeyState 
{ 
    LPARAM lparam;  

    struct  
    {   
     unsigned nRepeatCount : 16;   
     unsigned nScanCode : 8;   
     unsigned nExtended : 1;   
     unsigned nReserved : 4;   
     unsigned nContext  : 1;   
     unsigned nPrev  : 1;   
     unsigned nTrans  : 1;  
    }; 
}; 


KBDLLHOOKSTRUCT keyInfo = *((KBDLLHOOKSTRUCT*)lParam); 
KeyState myParam; 
myParam.nRepeatCount = 1; 
myParam.nScanCode  = keyInfo.scanCode; 
myParam.nExtended  = keyInfo.flags && LLKHF_EXTENDED; // maybe it should be keyInfo.flags & LLKHF_EXTENDED or keyInfo.flags >> LLKHF_EXTENDED 
myParam.nReserved  = 0;   
myParam.nContext  = keyInfo.flags && LLKHF_ALTDOWN;  
myParam.nPrev   = 0; // can store the last key pressed as virtual key/code, then check against this one, if its the same then set this to 1 else do 0 
myParam.nTrans   = keyInfo.flags && LLKHF_UP; 


// Or maybe I shd do this to transfer bits... 
myParam.nRepeatCount = 1; 
myParam.nScanCode  = keyInfo.scanCode; 
myParam.nExtended  = keyInfo.flags & 0x01; 
myParam.nReserved  = (keyInfo.flags >> 0x01) & (1<<3)-1;  
myParam.nContext  = keyInfo.flags & 0x05;  
myParam.nPrev   = 0;  // can store the last key pressed as virtual key/code, then check against this one, if its the same then set this to 1 else do 0 
myParam.nTrans   = keyInfo.flags & 0x07; 
+0

對於DWORD和位,簡單的位操作是足夠'UINT bit_test(X,BITNUM){返回X&(1個<< BITNUM)}' –

回答

0

如果要合併兩個位,你會用|位或)操作:

myParam.nExtended = keyInfo.flags | LLKHF_EXTENDED;

myParam.nExtended = keyInfo.flags | 0x01;

要檢查是否位被設置,你可以使用&按位與)操作:

if(myParam.nExtended & LLKHF_EXTENDED) ...

+0

不能與位域,只要使用myParam.nExtended = 1;這個答案中的代碼只能用於分配lparam。不是OP要求的。 –

0

不是

myParam.nExtended = keyInfo.flags && LLKHF_EXTENDED 

你需要

myParam.nExtended = (keyInfo.flags & LLKHF_EXTENDED) != 0; 

它是&不是&&,因爲你想要一個按位和不是邏輯和。並且!=0確保答案是0或1(而不是0或某個其他非零值),因此它可以表示在您的一位位域中。

0
CheckBits(DWORD var, DWORD mask) 
{ 
    DWORD setbits=var&mask; //Find all bits are set 
    DWORD diffbits=setbits^mask; //Find all set bits that differ from mask 
    return diffbits!=0; //Retrun True if all specific bits in variable are set 
} 
+3

不要張貼代碼只回答 – MickyD

+0

而這個代碼塊可能會回答這個問題;請嘗試通過在代碼中添加相關說明來改善您的答案。請參閱http://stackoverflow.com/help/how-to-answer – SMR

相關問題