测试是否在DWORD标志中设置了特定的位
Testing whether specific bits are set in a DWORD flag
我有一个DWORD变量&我想测试其中是否设置了特定的位。我下面有我的代码,但我不确定我是否从win32数据类型KBDLLHOOKSTRUCT传输到我的lparam数据类型正确?
请参阅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;
而不是
myParam.nExtended = keyInfo.flags && LLKHF_EXTENDED
你需要myParam.nExtended = (keyInfo.flags & LLKHF_EXTENDED) != 0;
是&
而不是&&
,因为您想要按位的和而不是逻辑的和。!=0
确保答案是0或1(而不是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
}
如果您想合并两个位,您将使用 |
(位或)运算符:
myParam.nExtended = keyInfo.flags | LLKHF_EXTENDED;
myParam.nExtended = keyInfo.flags | 0x01;
检查bit是否设置了,可以使用 &
(bitwise AND)运算符:
if(myParam.nExtended & LLKHF_EXTENDED) ...
相关文章:
- 是否允许使用带有"w+"模式的 freopen 进行标准设置?
- 是否可以使用智能指针成员设置具有另一个结构的结构?
- 如果我在相应 char 数组的声明中为其提供额外的元素,是否会自动设置 NULL?
- 是否有任何区域设置会影响宽字符编码?
- 由 JOB 中的进程启动的子进程是否可以将 JOB 属性设置为脱离作业?
- 是否可以为boost::random::uniform_int_distribution<>设置确定性种子?
- 是否可以在单独的线程中将 QObject 设置为 QML 上下文属性?
- 如果事件在仍在执行时再次设置,RegisterWaitForSingleObject 是否会并行运行回调?
- 在 c++ 中将对象设置为等于同一类的构造函数是否有效?
- 是否强制转换void**并将第一个字节设置为nullptr
- 是否可以为一个循环设置多个条件
- 检查是否至少设置了一点而不跳跃
- 我是否正确设置了此哈希表?
- 除了 rand() 之外,是否有任何随机生成器库,开发人员可以手动设置种子?
- 如何检查 int 中是否恰好设置了一位?
- 我是否必须在类中的所有变量C++设置为 private?
- 是否可以在C++中使用初始化列表设置数组的特定成员?
- 区域设置是否有定义负号的方面?
- 免疫表中副本的设置是否安全,避免线程损坏
- 使用UTC来回转换日期以忽略DST但仍使用当前用户的有效区域设置是否安全