|
|
|
|
||
关于内存读写文本字串的方法有很多,今天有空列举两种方法:
'声明API函数
Private Declare Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpClassName As String, ByVal lpWindowName As String) As Long
Private Declare Function GetWindowThreadProcessId Lib "user32" (ByVal hwnd As Long, lpdwProcessId As Long) As Long
Private Declare Function OpenProcess Lib "kernel32" (ByVal dwDesiredAccess As Long, ByVal bInheritHandle As Long, ByVal dwProcessId As Long) As Long
Private Declare Function WriteProcessMemory Lib "kernel32" (ByVal hProcess As Long, lpBaseAddress As Any, lpBuffer As Any, ByVal nSize As Long, lpNumberOfBytesWritten As Long) As Long
Private Declare Function ReadProcessMemory Lib "kernel32" (ByVal hProcess As Long, lpBaseAddress As Any, lpBuffer As Any, ByVal nSize As Long, lpNumberOfBytesWritten As Long) As Long
Private Declare Function CloseHandle Lib "kernel32" (ByVal hObject As Long) As Long
'常数
Const STANDARD_RIGHTS_REQUIRED = &HF0000
Const SYNCHRONIZE = &H100000
Const PROCESS_ALL_ACCESS = STANDARD_RIGHTS_REQUIRED Or SYNCHRONIZE Or &HFFF
'定义全局变量
Dim hProcess As Long
'指定内存地址写入文本字串方法一:
Private Sub Command1_Click()
Dim MyStr As String '要写入的文本字串
Dim ReadStr As String '读取已经写入的文本字串
MyStr = Space(53)
MyStr = "大家好!欢迎进入[潇潇的编程网站],http://www.wgbcw.cn"
If hProcess <> 0 Then
WriteProcessMemory hProcess, ByVal &H420060, ByVal MyStr, 53, 0&
Else
Debug.Print "记事本没运行,请先运行记事本。"
End If
ReadStr = Space(53)
ReadProcessMemory hProcess, ByVal &H420060, ByVal ReadStr, 53, 0&
If ReadStr <> "" Then
Debug.Print "写入文本字符====" & ReadStr & "====成功"
Else
Debug.Print "写入文本字符失败,请检查内存地址是否可写。"
End If
End Sub
'指定内存地址写入文本字串方法二:
Private Sub Command2_Click()
Dim MyStr As String '要写入的文本字串
Dim b() As Byte '字符数组
Dim bLen As Long '字符数组长度
Dim ReadStr As String '读取已经写入的文本字串
MyStr = "大家好!欢迎进入[潇潇的编程网站],http://www.wgbcw.cn"
b() = StrConv(MyStr, vbFromUnicode)
bLen = UBound(b)
If hProcess <> 0 Then
WriteProcessMemory hProcess, ByVal &H420060, ByVal VarPtr(b(0)), bLen + 1, 0&
Else
Debug.Print "记事本没运行,请先运行记事本。"
End If
ReadStr = Space(44)
ReadProcessMemory hProcess, ByVal &H420060, ByVal ReadStr, bLen + 1, 0&
If ReadStr <> "" Then
Debug.Print "写入文本字符====" & ReadStr & "====成功"
Else
Debug.Print "写入文本字符失败,请检查内存地址是否可写。"
End If
End Sub
Private Sub Form_Load()
Dim ck_hwnd As Long
Dim pid As Long
ck_hwnd = FindWindow("Notepad", "无标题 - 记事本")
GetWindowThreadProcessId ck_hwnd, pid
hProcess = OpenProcess(PROCESS_ALL_ACCESS, False, pid)
End Sub
Private Sub Form_Unload(Cancel As Integer)
CloseHandle hProcess
End Sub