指挥鼠标事件[DllImport(“user32.dll”)]点击,双击

时间:2012-01-05 08:21:53

标签: c# user32

我试过了 [的DllImport( “USER32.DLL”)] static extern bool SetCursorPos(int X,int Y);

将光标移动到所需的位置非常合适。我从来没有尝试过这种类型的DLL导入,但它的工作原理:)。但是我想要更多我还能提取什么? 主要是我想双击,点击或使用滚轮选项而无需任何鼠标输入,只是代码我该怎么做?以及如何查看user32dll中还包含哪些内容?

感谢名单

3 个答案:

答案 0 :(得分:12)

[DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
public static extern void mouse_event(uint dwFlags, uint dx, uint dy, uint cButtons, UIntPtr dwExtraInfo);
private const uint MOUSEEVENTF_LEFTDOWN = 0x02;
private const uint MOUSEEVENTF_LEFTUP = 0x04;
private const uint MOUSEEVENTF_RIGHTDOWN = 0x08;
private const uint MOUSEEVENTF_RIGHTUP = 0x10;

您应该使用Win32API

导入和定义这些常量以使用鼠标

使用以下方法执行鼠标操作

void sendMouseRightclick(Point p)
{
    mouse_event(MOUSEEVENTF_RIGHTDOWN | MOUSEEVENTF_RIGHTUP, p.X, p.Y, 0, 0);
}

void sendMouseDoubleClick(Point p)
{
    mouse_event(MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP, p.X, p.Y, 0, 0);

Thread.Sleep(150);

    mouse_event(MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP, p.X, p.Y, 0, 0);
}

void sendMouseRightDoubleClick(Point p)
{
    mouse_event(MOUSEEVENTF_RIGHTDOWN | MOUSEEVENTF_RIGHTUP, p.X, p.Y, 0, 0);

    Thread.Sleep(150);

    mouse_event(MOUSEEVENTF_RIGHTDOWN | MOUSEEVENTF_RIGHTUP, p.X, p.Y, 0, 0);
}

void sendMouseDown()
{
    mouse_event(MOUSEEVENTF_LEFTDOWN, 50, 50, 0, 0);
}

void sendMouseUp()
{
    mouse_event(MOUSEEVENTF_LEFTUP, 50, 50, 0, 0);
}

如果你想做一个鼠标拖动你应该首先发送MouseDown(鼠标点击)并保持它在更改鼠标位置时单击而不是发送鼠标(释放点击)这样的事情。

sendMouseDown();
Cursor.Position = new Point(30,30);
sendMouseUp();

答案 1 :(得分:5)

使用long类型会引发" PInvoke"错误。

我们应该使用int类型:

[DllImport("user32.dll")]
static extern void mouse_event(int dwFlags, int dx, int dy, 
                      int dwData, int dwExtraInfo);

[Flags]
public enum MouseEventFlags
{
    LEFTDOWN = 0x00000002,
    LEFTUP = 0x00000004,
    MIDDLEDOWN = 0x00000020,
    MIDDLEUP = 0x00000040,
    MOVE = 0x00000001,
    ABSOLUTE = 0x00008000,
    RIGHTDOWN = 0x00000008,
    RIGHTUP = 0x00000010
}

public static void LeftClick(int x, int y)
{
    Cursor.Position = new System.Drawing.Point(x, y);
    mouse_event((int)(MouseEventFlags.LEFTDOWN), 0, 0, 0, 0);
    mouse_event((int)(MouseEventFlags.LEFTUP), 0, 0, 0, 0);
}

来源:http://www.pinvoke.net/default.aspx/user32.mouse_event

答案 2 :(得分:3)

查看pinvoke.net以获取可用API的列表。包含代码示例和import语句。您还可以展开左侧的选择以查看每个DLL的可用API。