views:

147

answers:

1

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.

+1  A: 

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.

Quartermeister
Seems to work. Thanks. (Still don't quite understand why but hey..)
MrPurpleStreak