Thursday, December 30, 2010

Kill Office Application programmatically

You can kill particular application from multiple applications.
Means create multiple application objects and try to kill it will destroy particular process.
Ex. Create multiple office word document programmatically so every time you open this application one process will create in Task Manager “Word.exe” so after some limited document open your PC will hang.
Due to this I added below code for remove completed process from PC as below code.



Hashtable myHashtable = null;
protected void btn_Click(object sender, EventArgs e)
{
// get process ids before running the excel codes
CheckCurrentApplicationProcesses();

//your code for open application like Word,Excel,Access etc....

KillApplication();

}

private void CheckCurrentApplicationProcesses()
{
Process[] AllProcesses = Process.GetProcessesByName("ApplicationName");
myHashtable = new Hashtable();
int iCount = 0;

foreach (Process ApplicationProcess in AllProcesses)
{
myHashtable.Add(ApplicationProcess.Id, iCount);
iCount = iCount + 1;
}
}

private void KillApplication()
{
Process[] AllProcesses = Process.GetProcessesByName("ApplicationName");

// check to kill the right process
foreach (Process ApplicationProcess in AllProcesses)
{
if (myHashtable.ContainsKey(ApplicationProcess.Id) == false)
SPSecurity.RunWithElevatedPrivileges(delegate()
{
ApplicationProcess.Kill();
});
}

AllProcesses = null;
}


Happy Coding !!!

No comments:

Post a Comment