2016-01-16 32 views
-6

我想按下一個按鈕,當按鈕被激活時,關閉我想要的應用程序。例如,如果我打開記事本,我想按下一個按鈕並關閉記事本。但由於某些原因,我不能使用killclose命令,因爲它用紅色標出。我正在用C#構建這個應用程序。這是代碼。我不能在我的代碼中使用「kill」進程。 (用紅色下劃線)

public EventHandler<SpeechRecognizedEventArgs> sRecognized { get; set; } 
    public Form1() 
    { 
     InitializeComponent(); 
    }   
    void sRecognize_SpeechRecognized(object sender, SpeechRecognizedEventArgs e) 
    { 
     if (e.Result.Text == "alice present") 
     { 
      SoundPlayer sndPlayer = new SoundPlayer(Ai.Properties.Resources.My_name_is_A_L_I_C_E); 
      sndPlayer.Play(); 
     } 

     if (e.Result.Text == "open notepad") 
     { 
      Process notepad = Process.Start("notepad.exe"); 
     } 

     if (e.Result.Text == "close notepad") 
     { 
      BtnN.PerformClick(); 
     } 
    } 
    private void BtnN_Click(object sender, EventArgs e) 
    { 
     Process notepad = Process.Kill("notepad.exe"); 
    } 
+1

'Kill'​​是一種實例方法,您試圖靜態調用它。找到你想要殺死的「notepad.exe」實例,創建一個Process並殺死它。 – CodeCaster

+0

另外,請努力在網上格式化您的代碼,以便它是可讀的。你有太多空白。 – Dai

+0

你喜歡讀自己的文章嗎? –

回答

0

讓我們變得非常簡單。創建一個Process字段並將其用於無處不在:

private Process pNotepad; //Process field 

void sRecognize_SpeechRecognized(object sender, SpeechRecognizedEventArgs e) 
{ 
    if (e.Result.Text == "alice present") 
    { 
     SoundPlayer sndPlayer = new SoundPlayer(Ai.Properties.Resources.My_name_is_A_L_I_C_E); 
     sndPlayer.Play(); 
    } 

    if (e.Result.Text == "open notepad") 
    { 
     //starting Process "notepad" 
     pNotepad = new Process(); 
     pNotepad.StartInfo.FileName = "notepad.exe"; 
     pNotepad.Start(); 
    } 

    if (e.Result.Text == "close notepad") 
    { 
     BtnN.PerformClick(); 
    } 
} 

private void BtnN_Click(object sender, EventArgs e) 
{ 
    //kill process if it is running 
    if(pNotepad != null && pNotepad.HasExited == false) 
     pNotepad.Kill(); 
} 
+0

它說這旁邊的pNotepad.startinfor.filename =「notepad.exe」對象引用未設置爲對象的實例。 –

+0

不應該有任何例外,我在那裏忘了一行。再試一次。複製我發佈的完整代碼片段。 – Shaharyar

+0

非常感謝!說實話! –

-1

正如在評論中提到,Process.Kill是實例方法,而不是靜態的方法,所以你需要有Process類的實例,以調用Kill方法。
您還應該考慮進程名稱不是進程的唯一標識符,因爲可以有多個具有相同名稱的進程。
之後,如果您想要基於名稱的所有進程,則可以使用以下代碼。

public static void KillProcess(string processName) 
{ 
    var process = Process.GetProcessesByName(processName); 

    foreach (var proc in process) 
    proc.Kill(); 
} 

當你對自己創建新的進程,則可以將該進程ID存儲在一個靜態變量

... 
public static int OpenedProcessId; 
... 
Process notepad = Process.Start("notepad.exe"); 
OpenedProcessId = process.Id; 
... 

(這是唯一標識符),並用它來殺死下面的代碼,具體過程。

public static bool KillProcess(int processId) 
{ 
    try 
    { 
    var process = Process.GetProcessById(processId); 
    process.Kill(); 
    return true; 
    } 
    catch (Exception ex) { return false; } 
} 
+0

如果我們需要一個實例,爲什麼不簡單記住在啓動過程時創建的'Process'實例?爲了應用程序的用戶,從不建議這樣的事情作爲答案。這很危險!如果我有5個記事本打開,1個由應用程序啓動,那麼您將殺死6個進程,並且我在5個進程中的所有工作都將丟失! –

+0

@ThomasWeller謝謝托馬斯的建議,當然可以。讓我修改我的答案,以便它更適合當前的問題上下文。 – tchelidze

+0

@ThomasWeller托馬斯,我已經提到你所警告的,請完整閱讀我的答案,而不僅僅是代碼。 – tchelidze

相關問題