Google
 

Saturday, March 31, 2007

Use System.Windows.Forms.SendKeys in C#

  1. The SendKeys class is in System.Windows.Forms name space

  2. using  System;
    using System.Diagnostics;
    using System.Windows.Forms ;
    using System.Threading;

    namespace ProcessSendKeys
    {
        
    /// <summary>
        
    /// Summary description for Class1.
        
    ///  </summary>
        class  Class1
        {
            
    /// <summary>
            
    /// The main entry point for the application.
            
    ///  </summary>
            [STAThread]
            
    static void Main(string [] args)
            {
                
    int pause =  1000// set pause to 0 to cause this script to
                                    
    // outrace notepad

                Process notePad 
    = new Process();
                notePad.StartInfo.FileName  
    = "notepad.exe ";
                notePad.EnableRaisingEvents 
    =  true;
                notePad.Exited 
    += new  System.EventHandler(Notepad_Exited);
                notePad.Start();

                
    if (notePad.WaitForInputIdle(pause)  && notePad.Responding)
                {
                    SendKeys.SendWait(
    "This is input to Notepad ");
                    System.Threading.Thread.Sleep(
    2000 );
                    
    //comment the following line to cause "unexpected" window to appear
                    SendKeys.SendWait("^a{delete} "); 
                }
                
    else
                {
                    Console.WriteLine (
    "Notepad not ready after "  + (pause/1000 + " seconds." );
                }

                sendWithSleep(
    "%" );
                sendWithSleep(
    "{Down}");
                
    for (int i  = 0; i <  6; i++)
                {
                    sendWithSleep(
    "{Right}");
                }

                sendWithSleep(
    "{Escape}");

                notePad.CloseMainWindow ();
                
    if (notePad.WaitForExit(pause*10 ))
                {
                    Console.WriteLine(
    "Notepad exited normally ");
                }
                
    else
                {
                    Console.WriteLine (
    "Notepad did not exit normally after " 
                        
    + (pause*10 )/1000 +  " seconds");
                }

            }

            
    private static  void sendWithSleep(string p)
            {
                SendKeys.SendWait(p);
                 Thread.Sleep(
    500);            
            }

            
    private  static void Notepad_Exited( object sender, System.EventArgs e)
            {
                Console.WriteLine(
    "Notepad Exited ");
            }
        }
    }
  3. d

--
Happy day, happy life!

No comments: