Click here to Skip to main content
15,893,161 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I developed a wpf application where I want to manage single application instances, and my requirement is to kill old instances and allow new instances to execute further.
i tried below code but i got System.ComponentModel.Win32Exception: 'Access is denied' error when i call runningProcess.Kill() method

What I have tried:

C#
[STAThread]
public static void Main()
{
    Process[] localByName = Process.GetProcessesByName("faceme");
    Process currentProcess = Process.GetCurrentProcess();
    int nProcessID = Process.GetCurrentProcess().Id;

    var runningProcess = (from process in Process.GetProcesses()
                          where
                            process.Id != currentProcess.Id &&
                            process.ProcessName.Equals(
                              currentProcess.ProcessName,
                              StringComparison.Ordinal)
                          select process).FirstOrDefault();

        if (runningProcess != null)
        {
            runningProcess.Kill();
        }

    MyApp.App app = new MyApp.App();
    app.InitializeComponent();
    app.Run();
}
Posted
Updated 1-Jan-18 8:53am
v2
Comments
PureNsanity 2-Jan-18 0:01am    
I'm going to take a guess... Is this because an application isn't closing out properly? And you want to kill any stranded/hung application when you start up a new instance?

 
Share this answer
 
Comments
Member 13135651 1-Jan-18 8:50am    
[DllImport("user32.dll")]
which method i need to extern from user32.dll for Process.Kill();
OriginalGriff 1-Jan-18 9:35am    
You want:

[DllImport(ExternDll.Kernel32, CharSet=System.Runtime.InteropServices.CharSet.Auto, SetLastError=true)]
public static extern bool TerminateProcess(SafeProcessHandle processHandle, int exitCode);

But ... it won't make any difference.
Read what the link says.
You're trying to kill a process that you don't have the permissions to kill. There are also system processes that not even an Administrator can kill.

There is no way around this.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900