如何在屏幕上的某个位置模拟鼠标单击? [英] How can I simulate a mouse click at a certain position on the screen?

查看:107
本文介绍了如何在屏幕上的某个位置模拟鼠标单击?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做的是操纵鼠标.出于我自己的目的,这将是一个简单的宏.所以它会将我的鼠标移动到屏幕上的某个位置并点击,就像我以一定的间隔点击一样.

What I want to do is to manipulate the mouse. It will be a simple macro for my own purposes. So it will move my mouse to certain position on the screen and click like I am clicking with certain interval.

推荐答案

这是一段使用非托管函数来模拟鼠标点击的代码:

Here's a code that is using unmanaged functions to simulate mouse clicks :

//This is a replacement for Cursor.Position in WinForms
[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 MOUSEEVENTF_LEFTDOWN = 0x02;
public const int MOUSEEVENTF_LEFTUP = 0x04;

//This simulates a left mouse click
public static void LeftMouseClick(int xpos, int ypos)
{
    SetCursorPos(xpos, ypos);
    mouse_event(MOUSEEVENTF_LEFTDOWN, xpos, ypos, 0, 0);
    mouse_event(MOUSEEVENTF_LEFTUP, xpos, ypos, 0, 0);
}

要保持鼠标按下特定的持续时间,您可以Sleep()正在执行此函数的线程,例如:

To keep the mouse pressed for a specific duration you can Sleep() the thread that is executing this function, for example :

mouse_event(MOUSEEVENTF_LEFTDOWN, xpos, ypos, 0, 0);
System.Threading.Thread.Sleep(1000);
mouse_event(MOUSEEVENTF_LEFTUP, xpos, ypos, 0, 0);

上面的代码将保持鼠标按下 1 秒,除非用户按下释放鼠标按钮.另外,请确保不要在主 UI 线程上执行此代码,因为它会导致挂起.

The above code will keep the mouse pressed for 1 second unless the user presses the releases the mouse button. Also, make sure to not execute this code on the main UI thread as it will cause it to hang.

这篇关于如何在屏幕上的某个位置模拟鼠标单击?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆