![](/img/trans.png)
[英]Kill process started with FullTrustProcessLauncher in UWP
[英]Kill excel process which was started by a specific application
我有一個控制台應用程序,我在其中打開許多excel應用程序來進行一些處理。 最后,我想殺死此控制台應用程序打開的所有Excel進程。 所以,我正在使用這樣的代碼:
System.Diagnostics.Process[] procs = System.Diagnostics.Process.GetProcesses();
for (int i = 0; i < procs.Length; i++)
{
if (procs[i].ProcessName == "EXCEL")
{
procs[i].Kill();
}
}
但是這段代碼會關閉我計算機中的所有excel應用程序,包括我的應用程序未打開的應用程序。 我的問題是,如何修改此代碼以僅關閉我的控制台應用程序打開的excel應用程序?
嘗試使用()。
using(var newExcelObject = ...){
// your code here
}
// closes the object you intialised above
一旦超出范圍,它將自動關閉該過程。 這將是關閉Excel流程的最簡單和最好的做法。
否則,您可以手動關閉/處置對象,而不是終止進程。
希望這會有所幫助。
我建議做一些包裝上(Excel) Process
,你可以在完成后調用Close
。
public class ExcelProcess
{
Process m_Process;
public ExcelProcess(/* parameters of your choice */)
{
// instantiate process and assign it to the m_Process variable
}
public ExcelProcess(int id)
{
// this will instantiate process object and hook to the process with specified process id
m_Process = Process.GetProcessById(id);
}
public void Close()
{
m_Process.Kill();
}
public override ToString()
{
// this will return process id as a string value
return m_Process.Id.ToString();
}
}
擁有像上面這樣的對象你可以:
1.通過將這些列表/數組序列化為某個文本文件(如.ToString()
),將“實例”從項目移動到項目
2.可以直接控制進程( ExcelProcess
每一個ExcelProcess
可以擁有自己的IPC來與外部進程通信,您可以重定向流來自進程)這將由此對象處理
3.當其他人關閉當前鏈接到該對象的應用程序時, 會感到困惑 。
擴展以上幾點,我們假定用戶不能關閉掛到您的應用程序ExcelProcess
。
您可以創建一個持有者對象/字段,然后可以序列化:
List<ExcelProcess> m_ExcelProcesses;
添加任何進程。
foreach(var process in Process.GetProcessesByName("excel"))
{
m_ExcelProcesses.Add(new ExcelProcess(process.Id));
}
現在假設你要在另一個應用程序中關閉它們:
byte[] nl = new byte[2] { 0x0D, 0x0A }; // new line
using (FileStream fs = File.Create("C:\SomeArbitrary\PathToFile.txt"))
{
foreach(ExcelProcess proc in m_Processes)
{
byte[] b = BitConverter.GetBytes(int.Parse(proc.ToString()));
fs.Write(b, 0, b.Length);
fs.Write(nl, 0, nl.Length);
}
}
之后在你的新進程中負責關閉那些只讀取所有值並重寫文件(或刪除它)。
byte[] pidBytes = new byte[4]; // we stored int which is 4 bytes wide;
using (FileStream fs = File.OpenRead("C:\SomeArbitrary\PathToFile.txt"))
{
while(fs.CanRead)
{
fs.Read(pidBytes, 0, sizeof(int));
m_Processes.Add(new ExcelProcess(BitConverter.ToInt32(pidBytes, 0)));
fs.ReadByte(); // CR - 0x0D
fs.ReadByte(); // LF - 0x0A
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.