WPF 与winform获取鼠标坐标的差异

本文对比了WPF和WinForm中如何通过MouseDown事件获取鼠标点击位置的方法。WPF使用e.GetPosition方法获得相对坐标,而WinForm直接利用e.X和e.Y属性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  winform中以Panel为例的MouseDown事件为:

private void panelposition_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
{
      //分别用e.X,e.Y来获取鼠标的x,y坐标(e.X,e.Y分别为整数)
        int x=e.X;
        int y=e.Y;

  wpf中以Image为例的MouseDown事件为:

private void imageposition_MouseDown(object sender, MouseButtonEventArgs e)
{
        //采用e.GetPosition(IInputElement relativeTo)来获取鼠标的x,y坐标
        //以下部分来自于metadata中:
        //--------------------------------------------------------------
        // Summary:
        //     Returns the position of the mouse pointer relative to the specified element.
        //
        // Parameters:
        //   relativeTo:
        //     The element to use as the frame of reference for calculating the position
        //     of the mouse pointer.
        //
        // Returns:
        //     The x- and y-coordinates of the mouse pointer position relative to the specified
        //     object.
        public Point GetPosition(IInputElement relativeTo);
        //--------------------------------------------------------------
        //其中relativeTo为选择的对象,即在图片上面就是图片对象,窗体上面就是window对象。 
                //e.GetPosition(img).X为double类型,需转换后使用。      
                int x = Convert.ToInt32(e.GetPosition(img).X);
                int y = Convert.ToInt32(e.GetPosition(img).Y);

        }

  本文来自娜老汉的博客,原文地址:http://www.cnblogs.com/peasana/archive/2012/02/13/2349523.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值