Using Windows APIs from C#, again!






4.15/5 (26 votes)
How to trigger events for controls on another window running in another process.
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;
//Get a handle for the Calculator Application main window
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
{
//Get a handle for the "1" button
hwndChild = FindWindowEx((IntPtr)hwnd,IntPtr.Zero,"Button","1");
//send BN_CLICKED message
SendMessage((int)hwndChild,BN_CLICKED,0,IntPtr.Zero);
//Get a handle for the "+" button
hwndChild = FindWindowEx((IntPtr)hwnd,IntPtr.Zero,"Button","+");
//send BN_CLICKED message
SendMessage((int)hwndChild,BN_CLICKED,0,IntPtr.Zero);
//Get a handle for the "2" button
hwndChild = FindWindowEx((IntPtr)hwnd,IntPtr.Zero,"Button","2");
//send BN_CLICKED message
SendMessage((int)hwndChild,BN_CLICKED,0,IntPtr.Zero);
//Get a handle for the "=" button
hwndChild = FindWindowEx((IntPtr)hwnd,IntPtr.Zero,"Button","=");
//send BN_CLICKED message
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.