Introduction
This article shows how to control other windows and trigger events for their controls using Windows APIs.
In this sample, I simply get a handle for the Calculator window using the FindWindow
API, get a handle for the Calculator buttons using FindWindowEx
, and trigger the Button
Click
event for any required buttons, using the SendMessage
API.
Background
The main idea I want to demonstrate here is that any form/dialog in Windows must have a window handle; with this handle and using the windows related APIs, you can control the form/dialog and trigger events for its controls.
Here's the code. I think it is well commented and needs no more explanation:
int hwnd=0;
IntPtr hwndChild=IntPtr.Zero;
hwnd=FindWindow(null,"Calculator");
if(hwnd == 0)
{
if(MessageBox.Show("Couldn't find the calculator" +
" application. Do you want to start it?",
"TestWinAPI",
MessageBoxButtons.YesNo)== DialogResult.Yes)
{
System.Diagnostics.Process.Start("Calc");
}
}
else
{
hwndChild = FindWindowEx((IntPtr)hwnd,IntPtr.Zero,"Button","1");
SendMessage((int)hwndChild,BN_CLICKED,0,IntPtr.Zero);
hwndChild = FindWindowEx((IntPtr)hwnd,IntPtr.Zero,"Button","+");
SendMessage((int)hwndChild,BN_CLICKED,0,IntPtr.Zero);
hwndChild = FindWindowEx((IntPtr)hwnd,IntPtr.Zero,"Button","2");
SendMessage((int)hwndChild,BN_CLICKED,0,IntPtr.Zero);
hwndChild = FindWindowEx((IntPtr)hwnd,IntPtr.Zero,"Button","=");
SendMessage((int)hwndChild,BN_CLICKED,0,IntPtr.Zero);
}
Points of interest
I think controlling windows in other processes can be very helpful in many situations like:
- Ensuring that a main application is running before starting a dependant application.
- Automating some tasks.
I'm a senior software engineer experienced in C/C++ programming under different platforms. I like to get acquainted with new technologies that appear so fast day after day like the .NET framework, SQL 2008, etc.
Programming is both my profession and my main hobby.
I enjoy tickling with code using different programming languages on different platforms.