I am using an application that kills the process iexplore
(Internet Explorer) on a terminal server. The issue I am encountering is that I kill all processes of Internet Explorer on the terminal server, not just the one of the current user.
So if I log on as User1
and kill IE, it will be killed for User2
, User3
and so on ... I only want User1
's Internet Explorer to be killed. I use the following code to kill my process:
Private Sub ClearProcesses(ByVal ProcessName As String)
Dim myProcesses = Process.GetProcessesByName(ProcessName)
For Each Proc As Process In myProcesses
Try
Proc.Kill()
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Critical, "ClearProcess")
End Try
Next
End Sub
Is there a way to only kill the process for User1
?
You can use WMI to get the owner of a Process, and verify that the process is owned by the current user.
Using a Function like so:
Public Function GetProcessOwner(processId As Integer) As String
Dim query As String = "Select * From Win32_Process Where ProcessID = " + processId
Dim searcher As New ManagementObjectSearcher(query)
Dim processList As ManagementObjectCollection = searcher.[Get]()
For Each obj As ManagementObject In processList
Dim argList As String() = New String() {String.Empty, String.Empty}
Dim returnVal As Integer = Convert.ToInt32(obj.InvokeMethod("GetOwner", argList))
If returnVal = 0 Then
' argList(0) == User
' argList(1) == DOMAIN
Return argList(0)
End If
Next
Return "NO OWNER"
End Function
You should be able to do something like:
Private Sub ClearProcesses(ByVal ProcessName As String)
Dim myProcesses = Process.GetProcessesByName(ProcessName).Where(Function(p) GetProcessOwner(p.Id) = currentUser)
' Your current code...