Kill/Terminate process for current logged on user

Below is code that you can use to terminate processes that belong to the currently logged on user. This is using WMI and will work with all authenticated users, even non administrators.

You can use ExcludeMe to exclude a process, e.g. if you running a program and want to guarantee one instance on the machine, but it must not kill the current program.
KillProcesses(Process.GetCurrentProcess().ProcessName + “.exe”, false, Process.GetCurrentProcess());
The above will kill all other processes with same name, except the calling program.
e.g.

Download Source Code

e.g. KillProcesses(“chrome.exe”, true, null);

 public static void KillProcesses(string processName, bool currentUserOnly, Process excludeMe = null)
        {           
            var processes = new ManagementObjectSearcher(string.Format("SELECT * FROM Win32_Process WHERE  Name='{0}'", processName)).Get();
            foreach (var o in processes)
            {
                var process = (ManagementObject)o;
                var processId = int.Parse(process["ProcessId"].ToString());
                if (process["ExecutablePath"] == null) continue;
                if (excludeMe != null && processId == excludeMe.Id) continue;
                var ownerInfo = new object[2];
                process.InvokeMethod("GetOwner", ownerInfo);
                var owner = (string)ownerInfo[0];

                if (currentUserOnly)
                {
                    var windowsIdentity = WindowsIdentity.GetCurrent();
                    if (windowsIdentity == null) return;
                    var currentUser = windowsIdentity.Name;
                    if (currentUser.Contains(owner))
                        process.InvokeMethod("Terminate", null);
                }
                else
                    process.InvokeMethod("Terminate", null);
            }
        }

Download Source Code

Advertisement

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s