2012-03-21 412 views
1

我嘗試從我的C#代碼在Adobe Reader中打開2個pdf文件。讓我們稱他們爲A和B,然後A在B之前打開。如何從C#關閉PDF文件#

現在,當我嘗試殺死與文件A關聯的進程時,文件B也關閉,因爲它們鏈接到同一進程。是否有辦法關閉文件A而不關閉文件B.

另外,當我第一次嘗試殺死與文件B相關的進程時,沒有任何反應,並且文件B仍然保持打開狀態。

我該如何着手解決上述兩種情況。

我有這兩個文件的句柄。有沒有一種方法可以關閉手柄

+1

發佈啓動pdf並殺死它的代碼 – 2012-03-21 12:30:01

回答

2

聽起來對我來說,您應該使用Acrobat的Interapplication Communication API,它具有打開和關閉文檔的功能。與IAC(pdf documentation here)相比,你所做的相當不雅。

-1

我認爲一種方法是找到該程序實例並從應用程序中關閉它。這裏是一個如何找到窗口並關閉它的例子:http://www.mycsharpcorner.com/Post.aspx?postID=32

既然你有2個Adobe reader打開的實例,你會想確定哪個是哪個。您可以通過框架中的文字進行搜索。如果你有一個spy ++(或類似的替代品)的副本,它使得外部GUI組件的工作變得更加容易,因爲你可以找到那麼多關於該窗口的信息,包括名稱,窗口句柄等等。

1

您可以通過以下代碼找到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閱讀器的過程。

+1

這將殺死它找到的第一個Acrobat Reader,這將關閉文件A,文件B或兩者 - 誰知道?另外,對於OP而言,比對Brijesh更多,您如何知道最終用戶使用的是Adobe而不是其他某些PDF查看器?我們真的需要知道如何啓動PDF以知道如何殺死它。 – 2012-03-21 12:43:38

+0

@brijesh但是這也會關閉文件b,因爲相同的進程與文件B相關聯。我不想讓文件b關閉。 – 2012-03-21 12:45:12

+0

好吧,我明白了。有解決方案,您需要先關閉A,然後纔打開B.表示一次只打開一個PDF。所以沒有問題。 – 2012-03-21 13:21:52

0

TRY:
如果(clsProcess.ProcessName 包含(名稱)。)

INSTEAD:
如果(clsProcess.ProcessName StartsWith(名稱))

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");