我尝试从我的C#代码在Adobe Reader中打开2个pdf文件。让我们称他们为A和B,A在B之前打开。
现在当我尝试杀死与文件A相关联的进程时,文件B也会关闭,因为它们链接到同一进程。有没有办法关闭文件A而不关闭文件B.
此外,当我第一次尝试杀死与文件B关联的进程时,没有任何反应,文件B仍然保持打开状态。
我应该如何解决上述两种情况。
我有两个文件的处理。有没有办法可以关闭手柄
听起来像你应该使用Acrobat的Interapplication Communication API,它具有打开和关闭文档的功能。与IAC(pdf documentation here)相比,你所做的事情相当不优雅。
您可以通过以下代码找到A的PDF查看器的过程。
using System.Diagnostics;
public bool FindAndKillProcess(string name)
{
//here we're going to get a list of all running processes on
//the computer
foreach (Process clsProcess in Process.GetProcesses()) {
//now we're going to see if any of the running processes
//match the currently running processes by using the StartsWith Method,
//this prevents us from incluing the .EXE for the process we're looking for.
//. Be sure to not
//add the .exe to the name you provide, i.e: NOTEPAD,
//not NOTEPAD.EXE or false is always returned even if
//notepad is running
if (clsProcess.ProcessName.StartsWith(name))
{
//since we found the proccess we now need to use the
//Kill Method to kill the process. Remember, if you have
//the process running more than once, say IE open 4
//times the loop thr way it is now will close all 4,
//if you want it to just close the first one it finds
//then add a return; after the Kill
clsProcess.Kill();
//process killed, return true
return true;
}
}
//process not found, return false
return false;
}
然后调用上面的方法。
FindAndKillProcess("AcroRd32.exe");
所以你可以杀死PDF查看器的过程。
尝试: if(clsProcess.ProcessName.Contains(name))
代替: if(clsProcess.ProcessName.StartsWith(name))
using System.Diagnostics;
public bool FindAndKillProcess(string name)
{
foreach (Process clsProcess in Process.GetProcesses())
{
if (clsProcess.ProcessName.Contains(name))
{
//To know if it works
//MessageBox.Show(clsProcess);
clsProcess.Kill();
return true;
}
}
//process not found, return false
return false;
}
////// call the function:
FindAndKillProcess("AcroRd32");
////// if you have been saved all the variables also you can close you main form
FindAndKillProcess("Form_Name");
我认为这样做的一种方法是找到该程序的实例并从您的应用程序中关闭它。这是一个如何找到窗口并关闭它的例子:http://www.mycsharpcorner.com/Post.aspx?postID=32
由于您打开了2个Adobe Reader实例,因此您需要确定哪个是哪个。您可以按框架中的文本进行搜索。如果你有一个spy ++(或类似的替代品)的副本,它使得使用外部GUI组件变得更加容易,因为你可以找到关于该窗口的很多信息,包括名称,窗口句柄等等。