C#/winform 自动触发鼠标、键盘事件

要在C#程序中触发鼠标、键盘事件必须要调用windows函数。

一、鼠标事件的触发

 1.引用windows函数mouse_event

  

/// <summary>

        /// 鼠标事件

        /// </summary>

        /// <param name="flags">事件类型</param>

        /// <param name="dx">x坐标值(0~65535)</param>

        /// <param name="dy">y坐标值(0~65535)</param>

        /// <param name="data">滚动值(120一个单位)</param>

        /// <param name="extraInfo">不支持</param>

        [DllImport("user32.dll")]

        static extern void mouse_event(MouseEventFlag flags, int dx, int dy, uint data, UIntPtr extraInfo);

 MouseEventFlag表示鼠标事件的类型,可取多个枚举值组合。注意dx,dy参数,必须是绝对坐标(0,0)~(65535,65535)中的一点。

 /// <summary>

    /// 鼠标操作标志位集合

    /// </summary>

    [Flags]

    enum MouseEventFlag : uint

    {

        /// <summary>

        /// 鼠标移动事件

        /// </summary>

        Move = 0x0001,

 

        /// <summary>

        /// 鼠标左键按下事件

        /// </summary>

        LeftDown = 0x0002,

        LeftUp = 0x0004,

        RightDown = 0x0008,

        RightUp = 0x0010,

        MiddleDown = 0x0020,

        MiddleUp = 0x0040,

        XDown = 0x0080,

        XUp = 0x0100,

        Wheel = 0x0800,

        VirtualDesk = 0x4000,

        /// <summary>

        /// 设置鼠标坐标为绝对位置(dx,dy),否则为距离最后一次事件触发的相对位置

        /// </summary>

        Absolute = 0x8000

    }

2.调用mouse_event函数,触发鼠标事件

  /// <summary>

        /// 触发鼠标事件

        /// </summary>

        /// <param name="x"></param>

        /// <param name="y"></param>

        private static void DoMouseClick(int x, int y)

        {

            int dx = (int)((double)x / Screen.PrimaryScreen.Bounds.Width * 65535); //屏幕分辨率映射到0~65535(0xffff,即16位)之间

            int dy = (int)((double)y / Screen.PrimaryScreen.Bounds.Height * 0xffff); //转换为double类型运算,否则值为0、1

            mouse_event(MouseEventFlag.Move | MouseEventFlag.LeftDown | MouseEventFlag.LeftUp | MouseEventFlag.Absolute, dx, dy, 0, new UIntPtr(0)); //点击

        }

 

二、键盘事件的触发

1.引用windows函数keybd_event

/// <summary>

        /// 键盘事件

        /// </summary>

        /// <param name="bVk"> virtual-key code</param>

        /// <param name="bScan">hardware scan code</param>

        /// <param name="dwFlags"> flags specifying various function options</param>

        /// <param name="dwExtraInfo"> additional data associated with keystroke</param>

        [DllImport("user32.dll")]

        public static extern void keybd_event(byte bVk, byte bScan, int dwFlags, int dwExtraInfo);

bvk为键值,例如回车13,bScan设置为0,dwFlags设置0表示按下,2表示抬起;dwExtraInfo也设置为0即可。

2.调用keybd_event函数,触发键盘事件

   下面的代码演示触发Ctrl+C组合键,执行复制操作。

            keybd_event((byte)Keys.ControlKey, 0, 0, 0);

            keybd_event((byte)Keys.C, 0, 0, 0);

            keybd_event((byte)Keys.ControlKey, 0, 2, 0);

            keybd_event((byte)Keys.C, 0, 2, 0);

 

你可能感兴趣的:(WinForm)