日期:2014-05-18  浏览次数:20766 次

c#进程控制问题
private void button1_Click(object sender, EventArgs e)
  {
  Process[] p = Process.GetProcessesByName("War3");
  p[0].Kill();
  }

其他的进程都可以关闭,魔兽3的进程失败,求大大解释!

------解决方案--------------------
用这个方法关闭,100%成功,你的那个是要进程正常退出,因此失败。
C# code

        [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));
            }
        }