65.9K
CodeProject is changing. Read more.
Home

Using Windows APIs from C#, again!

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.15/5 (26 votes)

Jun 20, 2006

CPOL
viewsIcon

190355

downloadIcon

15454

How to trigger events for controls on another window running in another process.

Sample Image

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:

  1. Ensuring that a main application is running before starting a dependant application.
  2. Automating some tasks.