一、使用系统事件日志
1. 监控Windows事件日志
Imports System.Diagnostics
Public Class EventLogMonitor
Private WithEvents eventLog As New EventLog()
Public Sub New()
' 指定要监控的日志类型
eventLog.Log = "System" ' 也可以是 "Application", "Security"
eventLog.MachineName = "." ' 本地计算机
End Sub
Public Sub StartMonitoring()
AddHandler eventLog.EntryWritten, AddressOf OnEntryWritten
eventLog.EnableRaisingEvents = True
End Sub
Private Sub OnEntryWritten(ByVal source As Object, _
ByVal e As EntryWrittenEventArgs)
Dim entry As EventLogEntry = e.Entry
' 显示事件信息
Console.WriteLine("事件类型: " & entry.EntryType.ToString())
Console.WriteLine("时间: " & entry.TimeGenerated.ToString())
Console.WriteLine("来源: " & entry.Source)
Console.WriteLine("事件ID: " & entry.InstanceId)
Console.WriteLine("描述: " & entry.Message)
Console.WriteLine("----------------------")
End Sub
End Class
二、监控键盘和鼠标活动
2. 使用全局钩子(需要引用System.Windows.Forms)
Imports System.Runtime.InteropServices
Imports System.Windows.Forms
Public Class GlobalHook
Private Declare Function SetWindowsHookEx Lib "user32" _
Alias "SetWindowsHookExA" _
(ByVal idHook As Integer, _
ByVal lpfn As HookProc, _
ByVal hMod As IntPtr, _
ByVal dwThreadId As Integer) As IntPtr
Private Declare Function UnhookWindowsHookEx Lib "user32" _
(ByVal hhk As IntPtr) As Boolean
Private Declare Function CallNextHookEx Lib "user32" _
(ByVal hhk As IntPtr, _
ByVal nCode As Integer, _
ByVal wParam As IntPtr, _
ByVal lParam As IntPtr) As IntPtr
Private Const WH_KEYBOARD_LL As Integer = 13
Private Const WH_MOUSE_LL As Integer = 14
Private Delegate Function HookProc(ByVal nCode As Integer, _
ByVal wParam As IntPtr, _
ByVal lParam As IntPtr) As IntPtr
Private keyboardHook As IntPtr
Private mouseHook As IntPtr
Public Event KeyPressed As EventHandler(Of KeyPressEventArgs)
Public Event MouseActivity As EventHandler(Of MouseEventArgs)
Public Sub StartMonitoring()
' 安装键盘钩子
keyboardHook = SetWindowsHookEx(WH_KEYBOARD_LL, _
New HookProc(AddressOf KeyboardHookProc), _
Marshal.GetHINSTANCE(GetType(GlobalHook).Module), 0)
' 安装鼠标钩子
mouseHook = SetWindowsHookEx(WH_MOUSE_LL, _
New HookProc(AddressOf MouseHookProc), _
Marshal.GetHINSTANCE(GetType(GlobalHook).Module), 0)
End Sub
Private Function KeyboardHookProc(ByVal nCode As Integer, _
ByVal wParam As IntPtr, _
ByVal lParam As IntPtr) As IntPtr
If nCode >= 0 Then
Dim key As Keys = CType(wParam, Keys)
RaiseEvent KeyPressed(Me, New KeyPressEventArgs(Chr(key)))
End If
Return CallNextHookEx(keyboardHook, nCode, wParam, lParam)
End Function
Private Function MouseHookProc(ByVal nCode As Integer, _
ByVal wParam As IntPtr, _
ByVal lParam As IntPtr) As IntPtr
If nCode >= 0 Then
Dim x As Integer = Cursor.Position.X
Dim y As Integer = Cursor.Position.Y
RaiseEvent MouseActivity(Me, New MouseEventArgs( _
MouseButtons.None, 0, x, y, 0))
End If
Return CallNextHookEx(mouseHook, nCode, wParam, lParam)
End Function
End Class
三、监控进程活动
3. 监控进程启动和退出
Imports System.Diagnostics
Public Class ProcessMonitor
Private WithEvents timer As New Timer()
Public Sub New()
timer.Interval = 1000 ' 每秒检查一次
timer.Enabled = True
End Sub
Private Sub Timer_Tick(sender As Object, e As EventArgs) Handles timer.Tick
Dim currentProcesses As Process() = Process.GetProcesses()
For Each proc As Process In currentProcesses
' 记录进程信息
Console.WriteLine("进程名: " & proc.ProcessName)
Console.WriteLine("ID: " & proc.Id)
Console.WriteLine("启动时间: " & proc.StartTime.ToString())
Console.WriteLine("内存使用: " & proc.WorkingSet64 / 1024 & " KB")
Console.WriteLine("----------------------")
Next
End Sub
End Class
四、监控文件系统变化
4. 使用FileSystemWatcher
Imports System.IO
Public Class FileMonitor
Private WithEvents watcher As New FileSystemWatcher()
Public Sub New(ByVal pathToMonitor As String)
watcher.Path = pathToMonitor
watcher.IncludeSubdirectories = True
' 设置要监控的事件类型
watcher.NotifyFilter = NotifyFilters.FileName Or _
NotifyFilters.DirectoryName Or _
NotifyFilters.LastWrite
watcher.EnableRaisingEvents = True
End Sub
Private Sub OnChanged(ByVal source As Object, _
ByVal e As FileSystemEventArgs) _
Handles watcher.Changed
LogActivity("文件修改: " & e.FullPath & " - " & e.ChangeType.ToString())
End Sub
Private Sub OnCreated(ByVal source As Object, _
ByVal e As FileSystemEventArgs) _
Handles watcher.Created
LogActivity("文件创建: " & e.FullPath)
End Sub
Private Sub OnDeleted(ByVal source As Object, _
ByVal e As FileSystemEventArgs) _
Handles watcher.Deleted
LogActivity("文件删除: " & e.FullPath)
End Sub
Private Sub LogActivity(ByVal message As String)
Dim logFile As String = "ActivityLog.txt"
Dim logEntry As String = DateTime.Now.ToString() & " - " & message
File.AppendAllText(logFile, logEntry & Environment.NewLine)
Console.WriteLine(logEntry)
End Sub
End Class
五、监控网络活动
5. 使用网络流量统计
Imports System.Net.NetworkInformation
Public Class NetworkMonitor
Public Function GetNetworkStatistics() As String
Dim interfaces As NetworkInterface() = _
NetworkInterface.GetAllNetworkInterfaces()
Dim result As New StringBuilder()
For Each ni As NetworkInterface In interfaces
If ni.OperationalStatus = OperationalStatus.Up Then
Dim stats As IPv4InterfaceStatistics = ni.GetIPv4Statistics()
result.AppendLine("网络接口: " & ni.Name)
result.AppendLine("接收字节数: " & stats.BytesReceived)
result.AppendLine("发送字节数: " & stats.BytesSent)
result.AppendLine("----------------------")
End If
Next
Return result.ToString()
End Function
End Class
六、完整示例 - 简单活动监控器
Imports System.IO
Imports System.Threading
Public Class SimpleActivityMonitor
Private logFile As String = "ComputerActivity.log"
Private monitoring As Boolean = True
Public Sub StartMonitoring()
' 创建日志文件
Using writer As New StreamWriter(logFile, True)
writer.WriteLine("=== 监控开始于: " & DateTime.Now.ToString() & " ===")
End Using
' 启动监控线程
Dim monitorThread As New Thread(AddressOf MonitorActivities)
monitorThread.Start()
End Sub
Private Sub MonitorActivities()
While monitoring
Try
LogCurrentActivity()
Thread.Sleep(5000) ' 每5秒记录一次
Catch ex As Exception
' 处理异常
End Try
End While
End Sub
Private Sub LogCurrentActivity()
Dim logEntry As New StringBuilder()
' 记录时间
logEntry.AppendLine("时间: " & DateTime.Now.ToString())
' 记录活动窗口
Dim activeWindow As String = GetActiveWindowTitle()
logEntry.AppendLine("活动窗口: " & activeWindow)
' 记录磁盘使用情况
For Each drive As DriveInfo In DriveInfo.GetDrives()
If drive.IsReady Then
logEntry.AppendLine($"磁盘 {drive.Name}: " & _
$"空闲 {drive.AvailableFreeSpace / 1024 / 1024} MB / " & _
$"总共 {drive.TotalSize / 1024 / 1024} MB")
End If
Next
' 写入日志
Using writer As New StreamWriter(logFile, True)
writer.WriteLine(logEntry.ToString())
writer.WriteLine("----------------------")
End Using
End Sub
<Runtime.InteropServices.DllImport("user32.dll")>
Private Shared Function GetForegroundWindow() As IntPtr
End Function
<Runtime.InteropServices.DllImport("user32.dll", SetLastError:=True)>
Private Shared Function GetWindowText( _
ByVal hWnd As IntPtr, _
ByVal text As System.Text.StringBuilder, _
ByVal count As Integer) As Integer
End Function
Private Function GetActiveWindowTitle() As String
Const nChars As Integer = 256
Dim handle As IntPtr = GetForegroundWindow()
Dim Buff As New System.Text.StringBuilder(nChars)
If GetWindowText(handle, Buff, nChars) > 0 Then
Return Buff.ToString()
End If
Return "未知窗口"
End Function
Public Sub StopMonitoring()
monitoring = False
End Sub
End Class
使用说明
权限要求:部分功能需要管理员权限
隐私考虑:监控用户活动可能涉及隐私问题,请确保合法使用
性能影响:持续监控可能消耗系统资源
日志管理:定期清理日志文件,避免占用过多磁盘空间
注意事项
- 全局钩子可能导致系统不稳定
- 文件系统监控可能产生大量日志
- 监控他人计算机需获得明确授权
- 某些功能在64位系统上可能需要特殊处理
请根据实际需求选择合适的监控方法,并考虑性能、隐私和合法性等因素。