日期:2014-05-18 浏览次数:20766 次
[Flags] public enum ProcessAccessFlags : uint { All = 0x001F0FFF, Terminate = 0x00000001, CreateThread = 0x00000002, VMOperation = 0x00000008, VMRead = 0x00000010, VMWrite = 0x00000020, DupHandle = 0x00000040, SetInformation = 0x00000200, QueryInformation = 0x00000400, Synchronize = 0x00100000 } [DllImport("kernel32.dll")] static extern IntPtr OpenProcess(ProcessAccessFlags dwDesiredAccess, [MarshalAs(UnmanagedType.Bool)] bool bInheritHandle, uint dwProcessId); [DllImport("kernel32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] static extern bool TerminateProcess(IntPtr hProcess, uint uExitCode); [DllImport("kernel32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] static extern bool GetExitCodeProcess(IntPtr hProcess, out uint lpExitCode); private void KillProcess(string processId,string processName) { IntPtr killer; try { killer = OpenProcess(ProcessAccessFlags.All, false, uint.Parse(processId)); MessageBox.Show(killer.ToString()); uint exitcode = 0; bool ret = GetExitCodeProcess(killer, out exitcode); ret = TerminateProcess(killer, exitcode); if (ret) MessageBox.Show(string.Format("成功关闭程序{0}。", processName)); else { exitcode = 0; MessageBox.Show(string.Format("杀死进程{0}时失败,原因不明。", processName)); } } catch (Exception Exc) { MessageBox.Show(string.Format("杀死进程{0}时失败,原因是{1}。", processName, Exc.Message)); } }