A DWord in Windows is 32 bytes, which is equivalent to a Long in Visual Basic. The leftmost 16 bits comprise the low word (an Integer in VB), while the the rightmost 16 bits are the high word.
Most examples use an And operation to get or set the words in a DWord. However, the quickest way to get/set the high and low word of a DWord (Double Word) is to do a direct memory move operation. To do this we need one API declaration:
VB Code:
Private Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" _ (ByRef lpvDest As Any, _ ByRef lpvSrc As Any, _ ByVal cbLength As Long)
And four one-line functions, made into properties for easy and logical use.
VB Code:
Public Property Get LoWord(ByRef DWord As Long) As Integer CopyMemory LoWord, ByVal VarPtr(DWord), 2 End Property Public Property Let LoWord(ByRef DWord As Long, ByVal Word As Integer) CopyMemory DWord, Word, 2 End Property Public Property Get HiWord(ByRef DWord As Long) As Integer CopyMemory HiWord, ByVal VarPtr(DWord) + 2, 2 End Property Public Property Let HiWord(ByRef DWord As Long, ByVal Word As Integer) CopyMemory ByVal VarPtr(DWord) + 2, Word, 2 End Property
Using them is easy, here are some useless examples:
VB Code:
Dim lDWord As Long Dim iWord As Integer ' Set the low word LoWord(lDWord) = 1 ' Set the high word HiWord(lDWord) = 2 ' Get the low word iWord = LoWord(lDWord) ' Get the high word iWord = HiWord(lDWord)
Likewise, we can do the same for the high and low bytes of a Word:
VB Code:
Public Property Get LoByte(ByRef Word As Integer) As Byte CopyMemory LoByte, ByVal VarPtr(Word), 1 End Property Public Property Let LoByte(ByRef Word As Integer, ByVal LowByte As Byte) CopyMemory Word, LowByte, 1 End Property Public Property Get HiByte(ByRef Word As Integer) As Byte CopyMemory HiByte, ByVal VarPtr(Word) + 1, 1 End Property Public Property Let HiByte(ByRef Word As Integer, ByVal HighByte As Byte) CopyMemory ByVal VarPtr(Word) + 1, HighByte, 1 End Property
Have fun![]()




Reply With Quote