【问题标题】:Click on button in another program - FindWindow, C#单击另一个程序中的按钮 - FindWindow,C#
【发布时间】:2015-04-19 19:48:59
【问题描述】:

我正在尝试创建一个能够控制另一个程序(在 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("=");
}

是否可以模拟 CLICK on button?如何?可以在后台点击程序吗?

你能给我举个例子吗?

【问题讨论】:

标签: c# findwindow


【解决方案1】:

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

programmatically mouse click in another window

Send mouse clicks to X Y coordinate of another application

我希望他们有所帮助。

【讨论】:

  • 您好,谢谢您的回复,但我认为这个解决方案不在免费任务中?...?
【解决方案2】:

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

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

我认为没有其他方法可以做到这一点。

【讨论】:

  • @phawres 您可以将击键发送到活动应用程序,这是最接近“查看”作为后台操作的操作,请参阅上面的编辑。
  • @phawres 你只能通过访问某种 powershell、应用程序编程接口 (API)、宏或 dll 在后台执行此操作。如果应用程序不支持该类型的访问,则您不能以编程方式或作为后台操作进行。
猜你喜欢
  • 1970-01-01
  • 2011-06-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多