Click on button in another program - FindWindow, C#

本小妞迷上赌 提交于 2019-12-20 03:13:58

问题


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 ?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/28589908/click-on-button-in-another-program-findwindow-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!