将鼠标移动到位置并左键单击

Mat*_*ght 13 c# mousemove mouseclick-event sendinput

我正在使用C#,Framework 4(32位)的Windows窗体应用程序.

我有一个包含鼠标坐标的列表,我可以捕获它们.到现在为止还挺好.

但在某些时候,我想去那些坐标并点击鼠标左键.

这就是它现在的样子:

for (int i = 0; i < coordsX.Count; i++)
{
    Cursor.Position = new Point(coordsX[i], coordsY[i]);
    Application.DoEvents();
    Clicking.SendClick();
}
Run Code Online (Sandbox Code Playgroud)

点击课:

class Clicking
    {
        private const UInt32 MOUSEEVENTF_LEFTDOWN = 0x0002;
        private const UInt32 MOUSEEVENTF_LEFTUP = 0x0004;
        private static extern void mouse_event(
               UInt32 dwFlags, // motion and click options
               UInt32 dx, // horizontal position or change
               UInt32 dy, // vertical position or change
               UInt32 dwData, // wheel movement
               IntPtr dwExtraInfo // application-defined information
        );

        // public static void SendClick(Point location)
        public static void SendClick()
        {
            // Cursor.Position = location;
            mouse_event(MOUSEEVENTF_LEFTDOWN, 0, 0, 0, new System.IntPtr());
            mouse_event(MOUSEEVENTF_LEFTUP, 0, 0, 0, new System.IntPtr());
        }
    }
Run Code Online (Sandbox Code Playgroud)

但是我收到了这个错误:

Could not load type 'program.Clicking' from assembly 'program, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' because the method 'mouse_event' has no implementation (no RVA).
Run Code Online (Sandbox Code Playgroud)

我真的不明白问题是什么......你们知道问题是什么吗?或者你知道一个更好的方法来做我想做的事情吗?

Ser*_*lis 9

你有以下几行吗?

[DllImport("user32.dll")]
static extern void mouse_event(uint dwFlags, uint dx, uint dy, uint dwData,
   UIntPtr dwExtraInfo);
Run Code Online (Sandbox Code Playgroud)

这将导入功能mouse_eventuser32DLL,这是您要在程序中使用的.目前你的程序不知道DLL中的这个方法,直到你指定它来自哪个.

网站PInvoke.net user32鼠标事件对于这类事情的基础非常方便.

指导鼠标事件[DllImport("user32.dll")]点击,双击的答案也将对您的理解有很大帮助.

flags是你想要发送到mouse_input函数中的命令,在那个例子中你可以看到他正在发送两个mouse down并且mouse up在同一行中,这很好,因为mouse_event函数会将这些标志分开并连续执行它们.


另外请注意,这种方法已经被取代SendInput命令,一个很好的例子SendInput,并SetMousePos可以发现这个博客