Option Explicit
Private Declare Function OpenProcess Lib "kernel32" (ByVal dwDesiredAccess As Long, ByVal bInheritHandle As Long, ByVal dwProcessId As Long) As Long
Private Declare Function CloseHandle Lib "kernel32" (ByVal hObject As Long) As Long
Private Declare Function ReadProcessMemory Lib "kernel32.dll" (ByVal hProcess As Long, ByVal lpBaseAddress As Long, ByRef lpBuffer As Any, ByVal nSize As Long, ByRef lpNumberOfBytesWritten As Long) As Long
Private Const PROCESS_ALL_ACCESS = &H1F0FFF
'以二进制形式读取文件存放在FileBin()数组中
Public Sub ReadFileBin(FileBin() As Byte, FilePath As String)
Open FilePath For Binary As #1
ReDim FileBin(FileLen(FilePath))
While Not EOF(1)
Get #1, , FileBin
DoEvents
Wend
Close #1
End Sub
'读取内存进程代码存放在FileBin()数组中
Public Sub ReadExeBin(FileBin() As Byte, Pid As Long)
Dim Hand As Long
Hand = OpenProcess(PROCESS_ALL_ACCESS, False, Pid)
If Hand Then
ReDim FileBin(61440) As Byte
ReadProcessMemory Hand, &H971000, FileBin(0), 61440, 0&
End If
CloseHandle Hand
End Sub
'将要比较的特征码转化为Byte数组并存放在s2中
Private Sub StrBin(ByVal s1 As String, s2() As Byte)
Dim i As Long
ReDim s2(Len(s1) / 2 - 1) As Byte
For i = 0 To UBound(s2)
s2(i) = CByte("&H" & Mid(s1, i * 2 + 1, 2))
Next i
End Sub
'从s1中查找出特征码,并返回该特征码的首位置
Private Function StrStr(ByRef s1() As Byte, ByRef s2() As Byte) As Long
Dim c1 As Long, c2 As Long, i As Long, j As Long
c1 = UBound(s1): c2 = UBound(s2)
If c2 > c1 Then StrStr = -1: Exit Function
For i = 0 To c1 - c2
For j = 0 To c2 - 1
If (s1(i + j) <> s2(j)) Then Exit For
If (j = c2 - 1) Then StrStr = i: Exit Function
Next j
Next i
StrStr = -1
End Function
'Location:位置
'此函数的功能:返回特征码最后一个位置+j偏移的位置
Public Function Find_Location(ByRef FileBin() As Byte, s1 As String, Optional j As Long = 0) As Long
Dim i As Long, Str As String, s2() As Byte
StrBin s1, s2
i = StrStr(FileBin, s2)
If i = -1 Then
Find_Location = -1: Exit Function
End If
Find_Location = i + UBound(s2) + j
End Function