Attribute VB_Name = "MemoryLib"
Option Explicit

Public Declare Function CreateToolhelpSnapshot Lib "kernel32" Alias "CreateToolhelp32Snapshot" (ByVal lFlags As Long, ByVal lProcessID As Long) As Long
Public Declare Function ProcessFirst Lib "kernel32" Alias "Process32First" (ByVal hSnapShot As Long, uProcess As PROCESSENTRY32) As Long
Public Declare Function ProcessNext Lib "kernel32" Alias "Process32Next" (ByVal hSnapShot As Long, uProcess As PROCESSENTRY32) As Long
Public Declare Function Toolhelp32ReadProcessMemory Lib "Kernel32.dll" (ByVal th32ProcessID As Long, ByVal lpAddress As Long, lpBuffer As Any, ByVal cbRead As Long, lpNumberOfBytesRead As Long) As Long
Public Declare Sub CloseHandle Lib "kernel32" (ByVal hPass As Long)

Public Const TH32CS_SNAPPROCESS As Long = 2&
Public Const MAX_PATH As Integer = 260

Public Type PROCESSENTRY32
    dwSize As Long
    cntUsage As Long
    th32ProcessID As Long
    th32DefaultHeapID As Long
    th32ModuleID As Long
    cntThreads As Long
    th32ParentProcessID As Long
    pcPriClassBase As Long
    dwFlags As Long
    szExeFile As String * MAX_PATH
End Type

Private PID As Long
Private hSnapShot As Long
Private temp As String * 255

Private sPtr As String * 4
Private lPtr As Long

Private iStr As String * 2
Private iInt As Integer

'Load a memory profile into MemoryLib
Public Function InitAddress(ProcessName As String) As Boolean
    Dim uProcess As PROCESSENTRY32, R As Long

    temp = Space(255)
    If hSnapShot > 0 Then CloseHandles: PID = 0

    hSnapShot = CreateToolhelpSnapshot(TH32CS_SNAPPROCESS, 0&)
    uProcess.dwSize = Len(uProcess)
    R = ProcessFirst(hSnapShot, uProcess)

    InitAddress = False
    Do While R
        R = ProcessNext(hSnapShot, uProcess)
        If InStr(1, uProcess.szExeFile, ProcessName) > 0 Then PID = uProcess.th32ProcessID: InitAddress = True: Exit Do
    Loop
End Function

'Close the current memory profile
Public Sub CloseHandles()
    CloseHandle hSnapShot
    hSnapShot = 0
End Sub

'Used for getting strings
Public Function Peek(Address As Long, Bytes As Long) As String
    Call Toolhelp32ReadProcessMemory(PID, Address, ByVal temp, Bytes, 0)
    Peek = Left(temp, Bytes)
    temp = String(255, Chr(0))
End Function

Public Function Peek4(Address As Long) As Long
    sPtr = Peek(Address, 4)
    CopyMemory lPtr, ByVal sPtr, 4
    Peek4 = lPtr
End Function

Public Function Peek2(Address As Long) As Integer
    iStr = Peek(Address, 2)
    CopyMemory iInt, ByVal iStr, 2
    Peek2 = iInt
End Function

'Used for getting numbers
Public Function Portal(Address As Long, Count As Long) As Long
    Dim I As Integer, R As String, T As String, O As String

    O = Peek(Address, Count)

    For I = Count To 1 Step -1
        T = Hex(Asc(Mid(O, I, 1)))
        If Len(T) = 1 Then
            R = R + "0" + T
        Else
            R = R + T
        End If
    Next

    Portal = CLng("&H" + R)
End Function
