Answers for "c# wpf kill processes by username"

C#
1

c# wpf kill processes by username

using System.Security.Principal;
using System.Runtime.InteropServices;

public class ProcessManager {

	public static void KillProcessByNameAndUserName(string processName, string userName)
    {
        var processes = from p in Process.GetProcessesByName(processName)
                        where GetProcessUser(p) == userName
                        select p;

        foreach (Process p in processes) p.Kill();
    }


    private static string GetProcessUser(Process process)
    {
        IntPtr processHandle = IntPtr.Zero;
        try
        {
            OpenProcessToken(process.Handle, 8, out processHandle);
            WindowsIdentity wi = new WindowsIdentity(processHandle);
            string user = wi.Name;
            return user.Contains(@"\") ? user.Substring(user.IndexOf(@"\") + 1) : user;
        }
        catch
        {
            return null;
        }
        finally
        {
            if (processHandle != IntPtr.Zero)
            {
                CloseHandle(processHandle);
            }
        }
    }

    [DllImport("advapi32.dll", SetLastError = true)]
    private static extern bool OpenProcessToken(IntPtr ProcessHandle, uint DesiredAccess, out IntPtr TokenHandle);
    [DllImport("kernel32.dll", SetLastError = true)]
    [return: MarshalAs(UnmanagedType.Bool)]
    private static extern bool CloseHandle(IntPtr hObject);
}
Posted by: Guest on July-09-2021

C# Answers by Framework

Browse Popular Code Answers by Language