我有一个DWORD变量&我想测试是否在其中设置了特定的位。我的代码如下,但我不确定是否正在将win32数据类型KBDLLHOOKSTRUCT中的位正确传输到我的lparam数据类型?
请参阅记录DWORD标志变量的MSDN: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 :(得分:0)
如果要合并两位,可以使用 |
(按位OR )运算符:
myParam.nExtended = keyInfo.flags | LLKHF_EXTENDED;
myParam.nExtended = keyInfo.flags | 0x01;
要检查位是否已设置,您可以使用 &
(按位AND )运算符:
if(myParam.nExtended & LLKHF_EXTENDED) ...
答案 1 :(得分:0)
而不是
myParam.nExtended = keyInfo.flags && LLKHF_EXTENDED
你需要
myParam.nExtended = (keyInfo.flags & LLKHF_EXTENDED) != 0;
&
而不是&&
,因为您需要按位而不是逻辑和。并且!=0
确保答案为0或1(而不是0或其他非零值),因此它可以在您的一位位域中表示。
答案 2 :(得分: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
}