Click on button in another program - FindWindow, C#

phawresl picture phawresl · Feb 18, 2015 · Viewed 14.1k times · Source

I'm trying to create a program that will be able to control another program (in Windows).

I found this code:

// Get a handle to an application window.
[DllImport("USER32.DLL", CharSet = CharSet.Unicode)]
public static extern IntPtr FindWindow(string lpClassName,
                                       string lpWindowName);

// Activate an application window.
[DllImport("USER32.DLL")]
public static extern bool SetForegroundWindow(IntPtr hWnd);

//button event
private void button1_Click(object sender, EventArgs e)
{
    // Get a handle to the Calculator application. The window class 
    // and window name were obtained using the Spy++ tool.
    IntPtr calculatorHandle = FindWindow("CalcFrame", "Kalkulačka");

    // Verify that Calculator is a running process. 
    if (calculatorHandle == IntPtr.Zero)
    {
        MessageBox.Show("Calculator is not running.");
        return;
    }

    // Make Calculator the foreground application and send it  
    // a set of calculations.
    SetForegroundWindow(calculatorHandle);
    SendKeys.SendWait("111");
    SendKeys.SendWait("*");
    SendKeys.SendWait("11");
    SendKeys.SendWait("=");
}

Is is possible to simulate CLICK on button? How? It is possible to click on program in the background?

Can you show me an example ?

Answer