本人是C#初学者,写了一下一段代码,结果是:notepad没有关闭,但如果将程序中的if...else...注释掉却又可以了,不知道是怎么回事,往大家指点,谢谢 
using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Diagnostics; 
using System.Threading; namespace AutomationTestTraining 

    class Program 
    { 
        static void Main(string[] args) 
        { 
            try 
            { 
            Process myProcess = new Process(); 
            myProcess.StartInfo.FileName = "notepad.exe"; 
            myProcess.Start();             if (myProcess.Responding) 
                System.Console.WriteLine("Responding"); 
            else 
                System.Console.WriteLine("Not Responding");             Thread.Sleep(2000); 
            myProcess.CloseMainWindow(); 
            myProcess.Close();    
            }             catch(Exception e) 
            { 
                Console.WriteLine("Something wrong"); 
                Console.WriteLine(e.Message); 
            }         } 
    } 

解决方案 »

  1.   

    调试下是否有执行到
    myProcess.CloseMainWindow(); 
    这个代码?
      

  2.   

    Start 以后稍等一会就好了Process myProcess = new Process();
    myProcess.StartInfo.FileName = "notepad.exe";
    myProcess.Start();
    //add some time
    Thread.Sleep(2000);
    //get MainWindowHandle (just for verify you did get MainWindowHandle)
    IntPtr MainWindowHandle = myProcess.MainWindowHandle;
    if (myProcess.Responding)
        System.Console.WriteLine("Responding" + MainWindowHandle);
    else
        System.Console.WriteLine("Not Responding");Thread.Sleep(2000);
    myProcess.CloseMainWindow();
    myProcess.Close();
      

  3.   

    我单步走的时候,myProcess.CloseMainWindow()执行了,而且notepad也关了。为什么 ctrl+F5 或者F5 就不管用了呢? 
      

  4.   

    其实并不是myProcess.CloseMainWindow()失效,而是MainWindowHandle的值变了,你观察几次就明白了。如果MainWindowHandle=0了,就肯定不能关闭
      

  5.   

    The main window is the window that is created when the process is started. After initialization, other windows may be opened, including the Modal and TopLevel windows, but the first window associated with the process remains the main window.You can get the MainWindowHandle property only for processes that are running on the local computer. The MainWindowHandle property is a value that uniquely identifies the window that is associated with the process.A process has a main window associated with it only if the process has a graphical interface. If the associated process does not have a main window, the MainWindowHandle value is zero. If you have just started a process and want to use its main window handle, consider using the WaitForInputIdle method to allow the process to finish starting, ensuring that the main window handle has been created. Otherwise, an exception will be thrown.Windows 98, Windows Millennium Edition Platform Note: This property is not available on this platform if you started the process with ProcessStartInfo..::.UseShellExecute set to true. 
      
    ^_^