DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Automatically Send Keys To Other Application

05.29.2007
| 10743 views |
  • submit to reddit
        
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("=");
            }
        }
    }
}