Friday, August 17, 2007

Automatically send keys to other application

using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;

namespace ConsoleApplicationTest
{
   class Program
   {
       [System.Runtime.InteropServices.DllImport("USER32.DLL", CharSet = System.Runtime.InteropServices.CharSet.Auto)]
       static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
       [System.Runtime.InteropServices.DllImport("USER32.DLL", CharSet = System.Runtime.InteropServices.CharSet.Auto)]
       static extern bool SetForegroundWindow(IntPtr hWnd);

       static void Main(string[] args)
       {
           Process calc = Process.Start("calc.exe");
           calc.WaitForInputIdle();

           IntPtr calculatorHandle = FindWindow(null, "Calculator");
           if (calculatorHandle == IntPtr.Zero)
           {
               Console.WriteLine("Calculator is not running.");
           }
           else
           {
               SetForegroundWindow(calculatorHandle);
               SendKeys.SendWait("13");
               SendKeys.SendWait("*");
               SendKeys.SendWait("13");
               SendKeys.SendWait("=");
           }
       }
   }
} 

No comments:

Post a Comment