WPF Not sending MouseMove events after CaptureMouse(); - wpf

I'm trying to have a WPF canvas with rounded rectangles on that I can drag round using the mouse. However once I try and capture the mouse on the canvas I don't get the move events any more.
This is a "mycanvas" user control and the rectangles are "foo" user controls. The XAML for these (minus the preamble) are:
mycanvas.xaml:
<Canvas MouseDown="CanvasMouseDown" MouseMove="CanvasMouseMove" MouseUp="CanvasMouseUp" Background="White">
<my:Foo HorizontalAlignment="Left" Canvas.Left="97" Canvas.Top="30" x:Name="m_foo" VerticalAlignment="Top" Height="87" Width="128" />
</Canvas>
foo.xaml:
<Border BorderThickness="2" BorderBrush="Black" CornerRadius="15" Background="Plum">
<Grid>
<Label Content="Foo" Height="28" HorizontalAlignment="Left" Margin="6,6,0,0" Name="label1" VerticalAlignment="Top" />
</Grid>
</Border>
And then the handlers are:
mycanvas.xaml.cs:
private void CanvasMouseDown(object sender, MouseButtonEventArgs e)
{
if (e.Source is Foo)
{
m_moving = e.Source as Foo;
CaptureMouse();
e.Handled = true;
}
}
private void CanvasMouseMove(object sender, MouseEventArgs e)
{
if (m_moving != null)
{
Canvas.SetLeft(m_moving, e.GetPosition(this).X);
Canvas.SetTop(m_moving, e.GetPosition(this).Y);
}
}
private void CanvasMouseUp(object sender, MouseButtonEventArgs e)
{
ReleaseMouseCapture();
m_moving = null;
}
The MouseDown fires and so the CaptureMouse gets called (and works because I can no longer close the app or click anything else in it!) but the MouseMove never gets called anymore - so where do the MouseMove events get sent now???
If I alt-tab to another application and then go back now suddendly the MouseMove is called and the Foo moves with the mouse.

Try either:
Mouse.Capture(this, CaptureMode.SubTree);
or
m_moving.CaptureMouse();
...
if (m_moving != null)
{
m_moving.ReleaseMouseCapture();
m_moving = null;
}
The mouse events were being raised by the Foo, not by the Canvas, so when you capture the mouse with the Canvas you prevent them from being raised.

You can directly use the MouseMove event on the Window:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.MouseMove += MouseEventHandler;
}
private void MouseEventHandler(Object sender, MouseEventArgs e)
{
System.Windows.Point position = e.GetPosition(this);
Canvas.SetLeft(ElipseElement, position.X-5);
Canvas.SetTop(ElipseElement, position.Y-5);
}
}

Related

Draggable and clickable button

I'm trying to make button.
If user clicked/taped on it then click event fires.
If user pressed and hold and moved then drag window.
<DockPanel>
<Grid DockPanel.Dock="Top" x:Name="grid" PreviewMouseMove="Grid_PreviewMouseMove">
<Button Content="Button" Width="100" Height="50"
PreviewMouseLeftButtonDown="Button_PreviewMouseLeftButtonDown"/>
</Grid>
<ListBox x:Name="logListBox" Width="200" Height="200"/>
</DockPanel>
public partial class MainWindow : Window
{
private Point _startMousePosition;
public MainWindow()
{
InitializeComponent();
}
private void Button_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
logListBox.Items.Add("Left button event.");
_startMousePosition = e.GetPosition(grid);
}
private void Grid_PreviewMouseMove(object sender, MouseEventArgs e)
{
var currentMousePosition = e.GetPosition(grid);
var isMouseMoving = _startMousePosition.X != currentMousePosition.X ||
_startMousePosition.Y != currentMousePosition.Y;
if (e.LeftButton == MouseButtonState.Pressed && isMouseMoving)
{
DragMove();
logListBox.Items.Add("Drag window.");
}
}
}
But left button event fires in case of dragging (press and hold) and in case of single click (press and release).
Screenshot
How can i separate it?
How is it implemented usually?

Mouse click on WPF (Time)Slider has no effect when slider thumb is moving bound to a timer

I use MediaElement and (Time)Slider to play and control playing of a video.
I used answer 2 to this question as a base.
In addition to the dragging capability I would also like the slider thumb to be moved to a mouse click point.
This works ok when the MediaElement and (Time)Slider are paused, but when the video is playing a mouse click has no effect
Here is my code
XAML:
<MediaElement Source="..."
Name="mediaView"
Height="450" LoadedBehavior="Manual" UnloadedBehavior="Stop" Stretch="UniformToFill"
MediaOpened="OnMediaOpened" MediaEnded="OnMediaEnded" MediaFailed="OnMediaFailed" Grid.Row="0" Grid.Column="0"/>
<Grid Name="mediaBar" VerticalAlignment="Bottom" Margin="5,10,5,0" Background="#B2282828" Grid.Row="0" Grid.Column="0">
<!-- ... -->
<Slider Name="timeSlider" Margin="5,5,5,0"
Thumb.DragStarted="OnDragStarted" Thumb.DragCompleted="OnDragCompleted" ValueChanged="OnTimeSliderValueChanged"
PreviewMouseLeftButtonUp="OnMouseLeftButtonUp" IsMoveToPointEnabled="True"
MinWidth="200" FlowDirection="LeftToRight"
Grid.Column="4" Cursor="ScrollWE" VerticalAlignment="Center"/>
<!-- ... -->
</Grid>
relevant c# part:
private void OnDragStarted(object sender, DragStartedEventArgs args)
{
isDragging = true;
ticks.Stop();
}
private void OnDragCompleted(object sender, DragCompletedEventArgs args)
{
isDragging = false;
int SliderValue = (int)timeSlider.Value;
TimeSpan ts = new TimeSpan(0, 0, 0, 0, SliderValue);
mediaView.Position = ts;
if(currentStatus == Status.PLAYING)
ticks.Start();
}
private void OnMouseLeftButtonUp(object sender, EventArgs ea)
{
if(!isDragging)
{
mediaView.Pause();
ticks.Stop();
int SliderValue = (int)timeSlider.Value; // when video is playing this not the point of the mouse click
// ...
}
}
I can understand that timeSlider.Value delivers the current point in time instead of the mouse click position when the video is playing.
Is there another way to measure the position of the mouse click and update the slider value with that ?
Or a better solution for the Mouse-click-while-slider-is-running-situation ?
Try this:
private void OnMouseLeftButtonUp(object sender, MouseButtonEventArgs ea)
{
mediaView.Position = TimeSpan.FromSeconds((int)(mediaView.NaturalDuration.TimeSpan.TotalSeconds * (double)(ea.GetPosition(timeSlider).X / this.Width)));
}

WPF Popup wrapping when dragging vertically

I have a project that uses a System.Windows.Controls.Primatives.Popup to drag a 'tooltip' like control along with a mouse.
Whenever the drag crosses a horizontal line the popup 'wraps' to the bottom of the screen - despite having sane values for the VerticalOffset. The point at which this wrapping occurs appears to be tied to the HEIGHT of the window, but not it's position.
Here's the code from the sandbox project I have created that also exhibits the same behavior:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.MainGrid.MouseDown += Grid_MouseDown;
this.MainGrid.MouseUp += Grid_MouseUp;
this.MainGrid.MouseMove += (s, e) => { if (this.Popup.IsOpen) { Popup_Drag(s, e); } };
this.Popup.MouseMove += Popup_Drag;
}
private void Popup_Drag(object sender, MouseEventArgs e)
{
Popup.HorizontalOffset = e.GetPosition(this.Popup).X;
Popup.VerticalOffset = e.GetPosition(this.Popup).Y;
this.Status_Top.Text = String.Format("Height/Top: {0}/{1} Width/Left: {2}/{3}", this.Height, this.Top, this.Width, this.Left);
this.Status.Text = String.Format("Vertical Offset: {0} Horizontal Offset: {1}", Popup.VerticalOffset, Popup.HorizontalOffset);
}
private void Grid_MouseUp(object sender, MouseButtonEventArgs e)
{
this.Popup.IsOpen = false;
}
private void Grid_MouseDown(object sender, MouseButtonEventArgs e)
{
this.Popup.IsOpen = true;
Popup_Drag(sender, e);
}
}
And the Window XAML:
<Window x:Class="WpfSandbox.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 x:Name="MainGrid" Background="Purple">
<TextBlock x:Name="Status_Top"></TextBlock>
<Popup x:Name="Popup" Cursor="Hand" HorizontalAlignment="Left"
VerticalAlignment="Bottom" IsOpen="True">
<TextBlock Background="Blue" Foreground="White">
<TextBlock x:Name="Status">TEXT</TextBlock></TextBlock>
</Popup>
</Grid>
</Window>
I was able to fix this by adding Placement="RelativePoint" to the Popup attributes. Apparently this is the default in Silverlight, but not WPF.

Drag/Drop Button in same application throwing an exception

I have a Canvas that contains a button which I want to be able to drag and drop into another canvas. I want to copy the button to the other Canvas. Here is the code I am using:
The XAML:
<Window>
<Grid>
<Canvas
Height="300"
Width="500"
Background="Gray">
<Canvas
Name="cnvToolBox"
Canvas.Left="10"
Canvas.Top="10"
Background="AliceBlue"
Width="100"
Height="200">
<Button
Content="Drag Me!"
PreviewMouseLeftButtonDown="Button_PreviewMouseLeftButtonDown"
PreviewMouseMove="Button_PreviewMouseMove"></Button>
</Canvas>
<Rectangle
Canvas.Left="119"
Canvas.Top="9"
Width="102"
Height="202"
StrokeDashArray="0.5 1.0 0.3"
Stroke="Black"
StrokeThickness="2"/>
<Canvas
Name="cnvButtonDropZone"
Canvas.Left="120"
Canvas.Top="10"
Width="100"
Height="200"
Background="LightGreen"
AllowDrop="True"
DragEnter="Canvas_DragEnter"
Drop="Canvas_Drop">
</Canvas>
</Canvas>
</Grid>
</Window>
Here's the Code Behind:
public partial class MainWindow : Window
{
private Point startPoint;
public MainWindow()
{
InitializeComponent();
}
private void Button_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
startPoint = e.GetPosition(null);
}
private void Button_PreviewMouseMove(object sender, MouseEventArgs e)
{
Point currentPosition = e.GetPosition(null);
Vector diff = startPoint - currentPosition;
if (e.LeftButton == MouseButtonState.Pressed &&
(Math.Abs(diff.X) > SystemParameters.MinimumHorizontalDragDistance ||
Math.Abs(diff.Y) > SystemParameters.MinimumVerticalDragDistance))
{
Button button = sender as Button;
DataObject dragData = new DataObject("myFormat", button);
DragDrop.DoDragDrop(button, dragData, DragDropEffects.Copy);
}
}
private void Canvas_DragEnter(object sender, DragEventArgs e)
{
if (!e.Data.GetDataPresent("myFormat") || sender == e.Source)
{
e.Effects = DragDropEffects.None;
}
}
private void Canvas_Drop(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent("myFormat"))
{
Button button = e.Data.GetData("myFormat") as Button;
Canvas canvas = sender as Canvas;
canvas.Children.Add(button);
}
}
}
When I drop the button I get the following exception when I'm adding the button to the canvas:
Specified element is already the logical child of another element. Disconnect it first.
I'm just trying to learn how to drag and drop controls and not really sure what that error means and how to resolve it. I don't know where I'm going wrong. Any suggestions would be welcome.
Thanks!
The button is owned by its parent cnvToolBox. You need to remove it from cnvToolBox before adding it to the canvas.
cnvToolBox.Children.Remove(button);
var canvas = sender as Canvas;
canvas.Children.Add(button);
This moves the button from your toolbox to the canvas. If you actually want to clone the item you want something like:
if (e.Data.GetDataPresent("myFormat"))
{
var contentControl = (ContentControl)e.Data.GetData("myFormat");
var constructorInfo = contentControl.GetType().GetConstructor(new Type[] {});
if (constructorInfo != null)
{
var newElement = (UIElement)constructorInfo.Invoke(new object[]{});
var newContentControl = newElement as ContentControl;
if(newContentControl != null)
{
newContentControl.Content = contentControl.Content;
}
((Panel)sender).Children.Add(newElement);
}
}
It's because the Button already has a parent associated with it; the previous Canvas.
You can set the parent of the Button to null; which will essentially remove it from the logical relationship.
button.Parent = null;
You will then be able to add that Button to another Canvas as you have done in your code behind.
You can also remove the Button from the Children property directly if you prefer and then add it accordingly within the new Canvas.
Canvas.Children.Remove(button);

A draggable popup control in wpf

I need a draggable popup control in wpf and was wondering if any of your guys could help me out..I did see the following post:
Drag WPF Popup control
but that isnt how its supposed to work...? When i click and drag it always resets to a specific point and moreover the commenters said that this is not an efficient approach...?
Does anyone have any alternatives?
Thanks!
We can write a behavior to make any Popup draggable. Here is some sample XAML of a popup associated with a textbox that opens and stays open when the text box is focused:
<Grid>
<StackPanel>
<TextBox x:Name="textBox1" Width="200" Height="20"/>
</StackPanel>
<Popup PlacementTarget="{Binding ElementName=textBox1}" IsOpen="{Binding IsKeyboardFocused, ElementName=textBox1, Mode=OneWay}">
<i:Interaction.Behaviors>
<local:MouseDragPopupBehavior/>
</i:Interaction.Behaviors>
<TextBlock Background="White">
<TextBlock.Text>Sample Popup content.</TextBlock.Text>
</TextBlock>
</Popup>
</Grid>
Here is the behavior that allows us to drag the Popup:
public class MouseDragPopupBehavior : Behavior<Popup>
{
private bool mouseDown;
private Point oldMousePosition;
protected override void OnAttached()
{
AssociatedObject.MouseLeftButtonDown += (s, e) =>
{
mouseDown = true;
oldMousePosition = AssociatedObject.PointToScreen(e.GetPosition(AssociatedObject));
AssociatedObject.Child.CaptureMouse();
};
AssociatedObject.MouseMove += (s, e) =>
{
if (!mouseDown) return;
var newMousePosition = AssociatedObject.PointToScreen(e.GetPosition(AssociatedObject));
var offset = newMousePosition - oldMousePosition;
oldMousePosition = newMousePosition;
AssociatedObject.HorizontalOffset += offset.X;
AssociatedObject.VerticalOffset += offset.Y;
};
AssociatedObject.MouseLeftButtonUp += (s, e) =>
{
mouseDown = false;
AssociatedObject.Child.ReleaseMouseCapture();
};
}
}
If you are not familiar with behaviors, install the Expression Blend 4 SDK and add this namespaces:
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
and add System.Windows.Interactivity to your project.
You could open a child Window with a custom border layout. Then add a MouseDown handler that enables the dragging:
<Window
WindowStyle="None"
ShowInTaskbar="False"
ResizeMode="NoResize"
SizeToContent="Height"
MouseDown="Window_MouseDown">
...
</Window>
In code behind:
private void Window_MouseDown(Object sender, MouseButtonEventArgs e)
{
this.DragMove();
}

Resources