Monday, March 1, 2010

Simulating Keyboard Input with C# Part 2

A week ago, I was discussing how to simulate keyboard input into another application with C#. While the method of using GetProcessByName() works fine, it seems to be dependent on the Windows performance counters being enabled. I'm not sure if its just my Comodo Firewall which is blocking the writing to the restricted Windows area or its something else, but my old Visual Studio 2003 application could not successfully use the GetProcessByName() method that I used with my Visual Studio 2005 test. The FindWindow API call seems to be the more universal approach of getting the handle of another running Windows application.

To access, FindWindow or FindWindowByCaption, use the following pinvoke declarations:

[DllImport("user32.dll", SetLastError = true)]
static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

[DllImport("user32.dll", EntryPoint = "FindWindow", SetLastError = true)]
static extern IntPtr FindWindowByCaption(IntPtr ZeroOnly, string lpWindowName);

Use FindWindow() if you are searching using the registered "Class" name. Otherwise, if you want to use the text that appears on the Windows title bar, use the FindWindowByCaption() API call.

IntPtr hWnd;
if (externalAppType == "CLASS")
hWnd = FindWindow(externalAppName, null);
hWnd = FindWindowByCaption(IntPtr.Zero, externalAppName);
if (hWnd != IntPtr.Zero)
if (SetForegroundWindow(hWnd))
System.Windows.Forms.SendKeys.SendWait(id + "{ENTER}");

1 comment:

簡單嗎 said...
This comment has been removed by a blog administrator.