第一种
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Runtime.InteropServices; namespace WindowsApplication2 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { this.MouseClick+=new MouseEventHandler(Form1_MouseClick); } void Form1_MouseClick(object sender, MouseEventArgs e) { MessageBox.Show("X :" + e.X.ToString() + "Y :" + e.Y.ToString()); } private void button1_Click(object sender, EventArgs e) { int x=58; int y=32; //写法1 PostMessage(this.Handle, WM_LBUTTONDOWN, 0, (x & 0xFFFF) + (y & 0xFFFF) * 0x10000); PostMessage(this.Handle, WM_LBUTTONUP, 0, (x & 0xFFFF) + (y & 0xFFFF) * 0x10000); //简化下 其实就是Y坐标左移16位,然后再加上X坐标 PostMessage(this.Handle, WM_LBUTTONDOWN, 0, x + (y<<16)); PostMessage(this.Handle, WM_LBUTTONUP, 0, x+(y<<16)); } uint WM_LBUTTONDOWN = 0x201; uint WM_LBUTTONUP = 0x202; [DllImport("user32.dll", SetLastError = true)] static extern bool PostMessage(IntPtr hWnd, uint Msg, int wParam, int lParam); } }
查看Win32Api, point.Y << 16这个是移位操作(即yy×2的16次方),下面的point.X | (point.Y << 16),鼠标的xy坐标值做与操作,所以两个是一样的。
鼠标的坐标是以屏幕的像素点来计算的,从左上角分别为(x0,y0)。
原来或操作 高16位存放y轴坐标,低15位存放x轴坐标
第二种
Virtual mouse click c# Int32 word = MakeLParam(x, y); private int MakeLParam(int LoWord, int HiWord) { return ((HiWord << 16) | (LoWord & 0xffff)); } public static class SimInput { [DllImport("user32.dll")] static extern void mouse_event(uint dwFlags, uint dx, uint dy, uint dwData, UIntPtr dwExtraInfo); [Flags] public enum MouseEventFlags : uint { Move = 0x0001, LeftDown = 0x0002, LeftUp = 0x0004, RightDown = 0x0008, RightUp = 0x0010, MiddleDown = 0x0020, MiddleUp = 0x0040, Absolute = 0x8000 } public static void MouseEvent(MouseEventFlags e, uint x, uint y) { mouse_event((uint)e, x, y, 0, UIntPtr.Zero); } public static void LeftClick(Point p) { LeftClick((double)p.X, (double)p.Y); } public static void LeftClick(double x, double y) { var scr = Screen.PrimaryScreen.Bounds; MouseEvent(MouseEventFlags.LeftDown | MouseEventFlags.LeftUp | MouseEventFlags.Move | MouseEventFlags.Absolute, (uint)Math.Round(x / scr.Width * 65535), (uint)Math.Round(y / scr.Height * 65535)); } public static void LeftClick(int x, int y) { LeftClick((double)x, (double)y); } } public static void MouseLeftClick(Point p, int handle = 0) { //build coordinates int coordinates = p.X | (p.Y << 16); //send left button down SendMessage(handle, 0x201, 0x1, coordinates); //send left button up SendMessage(handle, 0x202, 0x1, coordinates); }
c