#729 – Mouse.GetPosition Doesn’t Work While Dragging
January 8, 2013 2 Comments
If you are handling the DragOver event during a drag-and-drop operation and you want to find the current mouse position, you need to use DragEventArgs.GetPosition, rather than the static Mouse.GetPosition method.
In the example below, we initiate a drag-and-drop operation in a window and then try reporting the mouse’s position in the window’s DragOver handler. We try using both methods to get the mouse position, but only the DragEventArgs.GetPosition method works.
<Window x:Class="WpfApplication2.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Application 2" Height="350" Width="325" MouseDown="Window_MouseDown" AllowDrop="True" DragOver="Window_DragOver"> <StackPanel> <Label Name="lblInfo1" Content="Info 1"/> <Label Name="lblInfo2" Content="Info 2"/> </StackPanel> </Window>
private void Window_MouseDown(object sender, MouseButtonEventArgs e) { DragDrop.DoDragDrop((DependencyObject)e.Source, "Sample", DragDropEffects.Copy); } private void Window_DragOver(object sender, DragEventArgs e) { System.Windows.Point p1 = Mouse.GetPosition(this); lblInfo1.Content = string.Format("Mouse.GetPosition: {0}, {1}", p1.X, p1.Y); System.Windows.Point p2 = e.GetPosition(this); lblInfo2.Content = string.Format("DragEventArgs.GetPosition: {0}, {1}", p2.X, p2.Y); }