phawresl
phawresl

Reputation: 105

Click on button in another program - FindWindow, C#

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 ?

Upvotes: 2

Views: 16590

Answers (2)

Dn24Z
Dn24Z

Reputation: 149

You can use the following code to simulate mouse click:

        [System.Runtime.InteropServices.DllImport("user32.dll")]
        static extern bool SetCursorPos(int x, int y);

        [System.Runtime.InteropServices.DllImport("user32.dll")]
        public static extern void mouse_event(int dwFlags, int dx, int dy, int cButtons, int dwExtraInfo);

        public const int MOUSE_LEFTDOWN = 0x02;
        public const int MOUSE_LEFTUP = 0x04;

        public static void LeftMouseClick(int x, int y)
        {
            SetCursorPos(x, y);
            mouse_event(MOUSE_LEFTDOWN, x, y, 0, 0);
            mouse_event(MOUSE_LEFTUP, x, y, 0, 0);
        }

Method LeftMouseClick is getting two parameters x and y representing coordinates on user screen:

LeftMouseClick(400, 200);

Or you can do it by keyboard: Link

private void button2_Click(object sender, EventArgs e)
    {          
       SendKeys.Send("{ENTER}");
    } 

basically that's what you are doing in your code:

SendKeys.SendWait("111");
SendKeys.SendWait("*");
SendKeys.SendWait("11");
SendKeys.SendWait("=");

I dont think there is another way of doing this.

Upvotes: 1

Taher A. Ghaleb
Taher A. Ghaleb

Reputation: 5240

You may find the answer in other posts:

programmatically mouse click in another window

or

Send mouse clicks to X Y coordinate of another application

I hope they help.

Upvotes: 1

Related Questions