Maybe many of you out there in Developer Land are already aware of this, but I need to point out that you can indeed shell, sleep, and SendKeys using the new fancy C# and .NET Framework. You see, a few months ago, I needed to come up with a quick and dirty demo of a Windows application. Then I came up with the brilliant notion of shelling to it, then sending keystrokes to it to demo the app. I wondered, can you still peform this most crude form of application interoperability with the most elegant C# and .NET?
The answer is a big YES! Check this C# code out:
using System;using System.Collections.Generic;using System.Text; using System.Diagnostics;using System.Threading;using System.Windows.Forms; namespace ConsoleApplication1{ class Program { static void Main(string[] args) { //"shell" to open WordPad Process myProcess = new Process(); myProcess.StartInfo.FileName = @"wordpad.exe"; myProcess.StartInfo.Verb = "Open"; myProcess.StartInfo.WindowStyle = ProcessWindowStyle.Normal; myProcess.Start(); //pause for 1/2 second Thread.Sleep(500); //open the Format dialog SendKeys.SendWait("%OF"); //set the font size, then ENTER SendKeys.SendWait("{TAB}{TAB}48~"); //type some text SendKeys.SendWait("Hello world"); } }}
using System;using System.Collections.Generic;using System.Text;
using System.Diagnostics;using System.Threading;using System.Windows.Forms;
namespace ConsoleApplication1{ class Program { static void Main(string[] args) { //"shell" to open WordPad Process myProcess = new Process(); myProcess.StartInfo.FileName = @"wordpad.exe"; myProcess.StartInfo.Verb = "Open"; myProcess.StartInfo.WindowStyle = ProcessWindowStyle.Normal; myProcess.Start(); //pause for 1/2 second Thread.Sleep(500); //open the Format dialog SendKeys.SendWait("%OF"); //set the font size, then ENTER SendKeys.SendWait("{TAB}{TAB}48~"); //type some text SendKeys.SendWait("Hello world"); } }}
The above code is a console EXE program that brings up WordPad, then types a big "Hello World", with a 0.5 second sleep in between to give WordPad time to open. I love this code -- it is SO old school. It warms my heart that you can still stoop to this level. I hope you enjoy it as much as I.
For a list of all of the SendKeys codes, see the following page in MSDN online:
http://msdn.microsoft.com/library/en-us/cpref/html/frlrfSystemWindowsFormsSendKeysClassTopic.asp
Happy coding!
- Eric