winfrom鼠标点击位置

时间:2023-01-20 21:20:33

//内容待整理


private void From1_MouseClick(object sender, MouseEventArgs e)

        {
            Point p = e.Location;
            string X = p.X.ToString();
            string Y = p.Y.ToString();
            MessageBox.Show(p.ToString(),X+Y);           

        }




API函数

[DllImport( "user32.dll" )]
         private  static  extern  bool  GetCursorPos( out  Point p);
 
使用
             Point p;
             GetCursorPos( out  p);



.Net封装好的方法

int x = Control.MousePosition.X;
int y = Control.MousePosition.Y;

用API方法

using System.Runtime.InteropServices;
Point p;
[DllImport("user32.dll")]
public static extern bool GetCursorPos(out Point pt);
private void timer1_Tick(object sender, EventArgs e)
{
GetCursorPos(out p);
label1.Text = p.X.ToString();//X坐标
label2.Text = p.Y.ToString();//Y坐标
}




可以用Control.MousePosition获得当前鼠标的坐标,使用PointToClient计算鼠标相对于某个控件的坐标,如下
Point screenPoint = Control.MousePosition;//鼠标相对于屏幕左上角的坐标
Point formPoint = this.PointToClient(Control.MousePosition);//鼠标相对于窗体左上角的坐标
Point contextMenuPoint = contextMenuStrip1.PointToClient(Control.MousePosition); //鼠标相对于contextMenuStrip1左上角的坐标