Unity 模拟鼠标自动点击事件

文章转自:http://www.jb51.net/article/54023.htm


有时需要自动调用鼠标点击事件,下面会满足需求:

using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using UnityEngine;

public class ImitateMouseClick : MonoBehaviour {

    /// 
    /// 鼠标事件
    /// 
    /// 事件类型
    /// x坐标值(0~65535)
    /// y坐标值(0~65535)
    /// 滚动值(120一个单位)
    /// 不支持
    [DllImport("user32.dll")]
    static extern void mouse_event(MouseEventFlag flags, int dx, int dy, uint data, UIntPtr extraInfo);

    /// 
    /// 鼠标操作标志位集合
    /// 
    [Flags]
    enum MouseEventFlag : uint
    {
        Move = 0x0001,
        LeftDown = 0x0002,
        LeftUp = 0x0004,
        RightDown = 0x0008,
        RightUp = 0x0010,
        MiddleDown = 0x0020,
        MiddleUp = 0x0040,
        XDown = 0x0080,
        XUp = 0x0100,
        Wheel = 0x0800,
        VirtualDesk = 0x4000,
        /// 
        /// 设置鼠标坐标为绝对位置(dx,dy),否则为距离最后一次事件触发的相对位置
        /// 
        Absolute = 0x8000
    }

    void Update()
    {
        if(Input.GetKeyDown(KeyCode.A))
        {
            Debug.Log("手动触发A键Down");
            DoMouseClick(600, 800);
        }

        if(Input.GetMouseButtonDown(0))
        {
            Debug.Log("模拟鼠标左键Down事件");
        }

        if (Input.GetMouseButtonUp(0))
        {
            Debug.Log("模拟鼠标左键Up事件");
        }
    }

    /// 
    /// 调用鼠标点击事件(传的参数x,y要在应用内才会调用鼠标事件)
    /// 
    /// 相对屏幕左上角的X轴坐标
    /// 相对屏幕左上角的Y轴坐标
    private static void DoMouseClick(int x, int y)
    {
        int dx = (int)((double)x / Screen.width * 65535); //屏幕分辨率映射到0~65535(0xffff,即16位)之间
        int dy = (int)((double)y / Screen.height * 0xffff); //转换为double类型运算,否则值为0、1
        mouse_event(MouseEventFlag.Move | MouseEventFlag.LeftDown | MouseEventFlag.LeftUp | MouseEventFlag.Absolute, dx, dy, 0, new UIntPtr(0)); //点击
    }
}

注意:要会利用好MouseEventFlag.Absolute来确定位置。

mouse_event(MouseEventFlag.LeftDown| MouseEventFlag.Absolute, dx, dy, 0, new UIntPtr(0)); //点击
DoMouseClick(600, 800);
这是相对左上角的位置。


mouse_event(MouseEventFlag.LeftDown, dx, dy, 0, new UIntPtr(0)); //点击
DoMouseClick(0, 0);
这是你当前鼠标的位置,这可以自动调用鼠标点击按钮。

你可能感兴趣的:(Unity)