加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – WPF无法从MouseDown事件获取触摸位置

发布时间:2020-12-15 22:01:39 所属栏目:百科 来源:网络整理
导读:我在将触摸支持添加到.NET(v 4.0)之前编写了一个 WPF项目,因此只处理了鼠标事件.我用手指在触摸屏上测试项目时遇到了这个问题. 问题是,在第一次触摸中正确检索位置(X,Y),但无论我在哪里触摸,即使我触摸图像,(X,Y)值在后续触摸中保持不变,MouseDown事件被触发
我在将触摸支持添加到.NET(v 4.0)之前编写了一个 WPF项目,因此只处理了鼠标事件.我用手指在触摸屏上测试项目时遇到了这个问题.

问题是,在第一次触摸中正确检索位置(X,Y),但无论我在哪里触摸,即使我触摸图像,(X,Y)值在后续触摸中保持不变,MouseDown事件被触发,这使它更奇怪.

它可以用.NET 3.0 / 3.5 / 4.0复制,在Win7 / Win8上测试,都是64位.似乎是MouseDown事件行为不端,MouseUp工作正常.

更新:

这是一个历史悠久的错误,MS尚未修复它(即使在4.5中),因此如果遇到相同的症状,则必须更新代码 – 从Touch事件获取触摸位置,而不是鼠标事件.幸运的是,这个错误不是很微妙,所以只需要一点时间来定位和修复.

重现问题的代码:

XAML:

<Window x:Class="WpfApplication1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Image Height="60" Width="80" x:Name="Image" MouseDown="Image_MouseDown" 
                Source="/WpfApplication1;component/Images/Desert.jpg" />
    </Grid> 
</Window>

代码背后:

using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WpfApplication1
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
        private void Image_MouseDown(object sender,MouseButtonEventArgs e)
        {
            Point p = e.GetPosition(Image);
            MessageBox.Show(p.X.ToString() + " " + p.Y.ToString());
        }
    }
}

解决方法

默认情况下,在WPF中,如果控件未处理Touch事件,则会将其提升为Mouse事件.触摸事件是路由事件,因此当触发鼠标事件时,它将在可视树上上下移动(因此即使您在图像外部触摸也会执行事件处理程序).

如果MouseDown事件来自提升的触摸事件,您可能使用StylusDevice获得正确的位置:

if (e.StylusDevice != null)
    point = e.StylusDevice.GetPosition(sender as Image);

或者作为替代方案,您可以为需要位置的控件添加TouchDown事件的处理程序:

<Image TouchDown="UIElement_OnTouchDown"/>

 private void UIElement_OnTouchDown(object sender,TouchEventArgs e)
 {
      var touchPoint = e.GetTouchPoint(sender as Image);
      // more processing using touchPoint.Position
 }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读