点击另一个程序中的按钮 - FindWindow,C#

时间:2015-02-18 17:26:10

标签: c# findwindow

我正在尝试创建一个能够控制其他程序的程序(在Windows中)。

我找到了这段代码:

// 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("=");
}

是否可以模拟点击按钮?怎么样?可以在后台单击程序吗?

你能告诉我一个例子吗?

2 个答案:

答案 0 :(得分:1)

您可以在其他帖子中找到答案:

programmatically mouse click in another window

Send mouse clicks to X Y coordinate of another application

我希望他们有所帮助。

答案 1 :(得分:1)

您可以使用以下代码模拟鼠标点击:

        [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);
        }

方法LeftMouseClick获取两个参数x和y,表示用户屏幕上的坐标:

LeftMouseClick(400, 200);

或者您可以通过键盘来完成: Link

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

基本上就是你在代码中所做的事情:

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

我认为还有另一种方法可以做到这一点。