I would li开发者_运维知识库ke to build a list of all processes generated by events in a form and kill them all when the form closes. How do I code this?
When I worked with the Excel Interop we had several processes created by it, and we had problems if we had real Excel workbooks opened at the same time the program was running.
If you kill the process and your user has a workbook opened, you might close their Excel instead. I would suggest getting a list of the PIDs for the processes that have Excel in their name before opening the workbook in your program, then get the list again immediately after opening it, and by seeing what is new determine the PID of your process. When you're done with the workbook, kill the process with the PID you retrieved.
Edit: when you open the workbook in code, a new process is created. Before opening the workbook, you have a list of processes - let's say 10 (by usingpart of the code Harendra wrote). Then you open the workbook, and get the list again - and you'll have 11 processes (you might have more, but only one of those is Excel). By comparing the two lists, you get the ID of the new process, which is your opened workbook. You add to a list or processes opened by you, and when closing the program, kill all the processes from the list.
Try this...
Process[] procList = Process.GetProcesses();
for (int i = 0; i <= procList.Length - 1; i ++) {
string strProcName = procList[i].ProcessName;
string strProcTitle = procList[i].MainWindowTitle();
//check for your process name.. here i m checking excel process
if (strProcName.ToLower().Trim().Contains("excel")) {
procList[i].Kill();
}
}
In continuation with reply from Harendra, you can store all the process ID of process invoked by you ! and close them at the time of closing.
This statement is valid only if you are using Process.Start to start processes
精彩评论