开发者

WPF Not sending MouseMove events after CaptureMouse();

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="开发者_如何学Python6,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);    


    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜