2016-09-23 102 views
0

如何等待(阻止)我的程序,直到我先前啓動的進程的特定對話框關閉?c#等待,直到啓動進程的對話框關閉

我正在啓動pageant.exe來加載ssh密鑰。 Pageant從類「Process」開始。這工作正常。

我的ssh密鑰有一個密碼。所以我的主程序/進程(這個啓動進程)必須等到用戶輸入ssh密鑰密碼。

我有一個想法如何等待,但不知道如何在c#中執行此操作: 如果選美會詢問密碼,將出現一個對話框。所以我的主程序/進程可以等到密碼對話框關閉。是否有可能在C#中做到這一點?

我從here得到了想法。

編輯:找到一個解決辦法

// wait till passphrase dialog closes 
if(WaitForProcessWindow(cPageantWindowName)) 
{ // if dialog/process existed check if passphrase was correct 
    do 
    { // if passphrase is wrong, the passphrase dialog is reopened 
     Thread.Sleep(1000); // wait till correct passphrase is entered 
     } while (WaitForProcessWindow(cPageantWindowName)); 
    } 
} 

private static bool WaitForProcessWindow(string pProcessWindowName) 
{ 
    Process ProcessWindow = null; 
    Process[] ProcessList; 
    bool ProcessExists = false; // false is returned if process is never found 


    do 
    { 
     ProcessList = Process.GetProcesses(); 
     ProcessWindow = null; 
     foreach (Process Process in ProcessList) 
     { // check all running processes with a main window title 
      if (!String.IsNullOrEmpty(Process.MainWindowTitle)) 
      { 
       if (Process.MainWindowTitle.Contains(pProcessWindowName)) 
       { 
        ProcessWindow = Process; 
        ProcessExists = true; 
       } 
      } 
     } 
     Thread.Sleep(100); // save cpu 
    } while (ProcessWindow != null); // loop as long as this window is found 
    return ProcessExists; 
} 
+1

我們通常不會在這裏將Perl腳本轉換爲C#。 [問]。還可以在[mcve] – MickyD

+0

處查看有趣的事實。這可能有助於http://stackoverflow.com/a/3147920/6248956 – YuvShap

回答

-1

這可能會幫助你,但不給你整個控制。我對選美不熟悉,所以我不確定它是否繼續在後臺運行。但如果程序自動關閉,您可以在應用程序中執行此操作。

因此,如果Pageant應用程序是否打開,您可以檢查一個循環,一旦它打開,您執行一些代碼,一旦它關閉,您再次啓用該程序。

在某些後臺工作人員執行此代碼。

//Lets look from here if pageant is open or not. 

    while(true) 
    { 
     if (Process.GetProcessesByName("pageant").Length >= 1) 
     { 
      //block your controls or whatsoever. 
      break; 
     } 
    } 

    //pageant is open 

    while(true) 
    { 
     if (!Process.GetProcessesByName("pageant").Length >= 1) 
     { 
      //enable controls again 
      break; 
     } 
    } 

    //close thread 
+0

所有這些都是檢查進程是否正在運行,而不是如果對話框處於打開狀態。再加上它最大限度地提高了CPU – MickyD