一个进程大多数情况下都不是直接启动,而是有使用参数的。比如我们双击一个文本文件,其实是它调用的notepad.exe然后将这个txt文件的完整路径传递给它,然后任务管理器里出现经常notepad.exe,有些任务管理器可以看到后面的命令行参数,你可以看到正是这个txt文件的完整路径。
有时我们需要得知这样的进程的参数,比如cmd.exe 我们需要看它执行的是哪个批处理文件,是否是病毒等非法调用的,这时可以通过任务管理器,但是通过vb编程也可以获取这个值的。下面的代码就是过程,主要是通过了windows系统的winmgmts对象来处理的。
Option Explicit Private Sub Form_Load() getProcessCommandLine "iexplore.exe" End Sub '得到所有进程名为proName的详细列表,参数一定要写完整。 Private Function getProcessCommandLine(ByVal proName As String) As String Dim objWMIService As Object Dim colProcessList As Object Dim objProcess As Object Dim objProType As Object Dim strResult As String Set objWMIService = GetObject("winmgmts:" & "{impersonationlevel=impersonate}!//./root/cimv2") Set colProcessList = objWMIService.ExecQuery("Select * from Win32_Process Where Name='" & proName & "'") If colProcessList.Count <> 0 Then For Each objProcess In colProcessList For Each objProType In objProcess.Properties_ If objProType.Name = "CommandLine" Then strResult = strResult & objProType.Value & vbCrLf Exit For End If Next Next End If If strResult <> "" Then getProcessCommandLine = strResult MsgBox strResult End If End Function
'杀掉包含指定参数的进程,这样可以区别杀掉指定某些进程 Private Function killProcessByPra(ByVal strProName$, ByVal strKeyPra$) As Boolean Dim objWMIService As Object Dim colProcessList As Object Dim objProcess As Object Dim objProType As Object Dim strResult As String Set objWMIService = GetObject("winmgmts:" & "{impersonationlevel=impersonate}!//./root/cimv2") Set colProcessList = objWMIService.ExecQuery("Select * from Win32_Process Where Name='" & strProName & "'") If colProcessList.Count <> 0 Then For Each objProcess In colProcessList For Each objProType In objProcess.Properties_ If objProType.Name = "CommandLine" Then If InStr(objProType.Value, strKeyPra) > 0 Then '如果包含指定关键字参数的进程就杀掉 objProcess.Terminate killProcessByPra = True End If End If Next Next End If End Function '检查是否包含指定关键字参数的进程,有的话就返回true Private Function isExistProcessByPra(ByVal strProName$, ByVal strKeyPra$) As Boolean Dim objWMIService As Object Dim colProcessList As Object Dim objProcess As Object Dim objProType As Object Dim strResult As String Set objWMIService = GetObject("winmgmts:" & "{impersonationlevel=impersonate}!//./root/cimv2") Set colProcessList = objWMIService.ExecQuery("Select * from Win32_Process Where Name='" & strProName & "'") If colProcessList.Count <> 0 Then For Each objProcess In colProcessList For Each objProType In objProcess.Properties_ If objProType.Name = "CommandLine" Then If InStr(objProType.Value, strKeyPra) > 0 Then '如果包含指定关键字参数的进程就返回true isExistProcessByPra = True Exit Function End If End If Next Next End If End Function