WPF 4 將每根手指視為獨立觸控裝置,分配唯一 ID 追蹤。三個基礎事件:
TouchDown:手指接觸螢幕。TouchMove:手指在螢幕移動。TouchUp:手指離開螢幕。<Canvas x:Name="touchPad" Background="Gray"
TouchDown="touchPad_TouchDown"
TouchMove="touchPad_TouchMove"
TouchUp="touchPad_TouchUp" />
private Dictionary<int, Ellipse> movingEllipses = new Dictionary<int, Ellipse>();
private Random rd = new Random();
private void touchPad_TouchDown(object sender, TouchEventArgs e)
{
Ellipse ellipse = new Ellipse
{
Width = 30,
Height = 30,
Stroke = Brushes.White,
Fill = new SolidColorBrush(Color.FromRgb(
(byte)rd.Next(0, 255),
(byte)rd.Next(0, 255),
(byte)rd.Next(0, 255)))
};
TouchPoint tp = e.GetTouchPoint(touchPad);
Canvas.SetTop(ellipse, tp.Bounds.Top);
Canvas.SetLeft(ellipse, tp.Bounds.Left);
movingEllipses[e.TouchDevice.Id] = ellipse;
touchPad.Children.Add(ellipse);
}
private void touchPad_TouchMove(object sender, TouchEventArgs e)
{
Ellipse ellipse = movingEllipses[e.TouchDevice.Id];
TouchPoint tp = e.GetTouchPoint(touchPad);
Canvas.SetTop(ellipse, tp.Bounds.Top);
Canvas.SetLeft(ellipse, tp.Bounds.Left);
}
private void touchPad_TouchUp(object sender, TouchEventArgs e)
{
movingEllipses.Remove(e.TouchDevice.Id);
Ellipse ellipse = movingEllipses[e.TouchDevice.Id]; // 註:原文有誤,應先取出再移除
touchPad.Children.Remove(ellipse);
}
影片:YouKu 觀看