Process.Kill() Access Denied

2019-06-15 02:27发布

问题:

When I run the following code, a Win32Exception is thrown for Access Denied. I cannot find any solutions via search. How do I fix this?

foreach (ListViewItem list in showprocesses.SelectedItems)
{
    Process p = System.Diagnostics.Process.GetProcessById(Convert.ToInt32(list.Tag));
    if (p != null)
        p.Kill();
}

回答1:

You will generally get this error if you do not have the necessary permissions. You must be an administrator, and in win vista and above, run your app/process in elevated mode. Furthermore, there are certain processes that even as admin you won't be able to kill, some deemed system critical, etc, and you may need to run as system, and then there are those that even system can't kill, like antivirus, or an actual virus, because they don't want you killing their process

Another possibility is that if the process is already terminating, it will also throw that exception, see MSDN



回答2:

I had this kind of problems with a Delphi application Under Windows 8.1 My application was closing, but was still in the background processes of the task manager. Impossible to kill it with TaskKill (tried admin mode, "/F" option, from command line...) Finally I found out that Windows "marked" a DLL of my application as "IgnoreFreeLibrary". That is why my application was not closing. Here is an extract of the registry :

[HKEY_CURRENT_USER\Software\Microsoft\Windows NT\CurrentVersion\AppCompatFlags\Layers]
"{MyApplicationPathAndExeName}"="$ IgnoreFreeLibrary<DllWithProblemName.Dll>"

I erased the registry entry and everything was back to normal.



回答3:

I had same problem and used these codes to solve the problem:

    [DllImport("user32.dll")]
    public static extern int FindWindow(string ClassName, string WindowName);

    [DllImport("user32.dll")]
    public static extern int SendMessage(int hWnd, uint Msg, int wParam, int lParam);

    public const int WM_SYSCOMMAND = 0x0112;
    public const int SC_CLOSE = 0xF060;

    private void button1_Click(object sender, RoutedEventArgs e)
    {
        int HWND = FindWindow(null, "My Window");//window title

        SendMessage(HWND, WM_SYSCOMMAND, SC_CLOSE, 0);
    }


回答4:

disable UAC on windows solve the problem.