即使光标位于画布外,也会调用MouseMove事件

时间:2013-09-20 13:46:07

标签: c# wpf canvas

我不知道我的代码或WPF是否有问题,但问题是:我想创建一个小程序,你可以在画布中用光标绘制。 我有一个简单的WPF窗口:

<Window x:Class="WpfApplication1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="475" Width="544">
<Grid>    
    <Grid.RowDefinitions>
        <RowDefinition Height="100px"></RowDefinition>
        <RowDefinition Height ="*"></RowDefinition>
        <RowDefinition Height="100px"></RowDefinition>
    </Grid.RowDefinitions>    
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="100px"></ColumnDefinition>
        <ColumnDefinition Width="*"></ColumnDefinition>
        <ColumnDefinition Width="100px"></ColumnDefinition>
    </Grid.ColumnDefinitions>
        <Canvas Grid.Row="1" Grid.Column="1"  Name="imageCanvas" MouseEnter="StackPanel_MouseEnter" MouseLeave="StackPanel_MouseLeave" Background="LightGray" 
                      MouseDown="StackPan_MouseDown" MouseUp="StackPan_MouseUp" MouseMove="StackPan_MouseMove">

        </Canvas>        
</Grid>

以下是背景代码:

   private void StackPan_MouseDown(object sender, MouseButtonEventArgs e)
    {
        draw = true;
    }

    private void StackPan_MouseUp(object sender, MouseButtonEventArgs e)
    {
        draw = false;
    }

    private void StackPan_MouseMove(object sender, MouseEventArgs e)
    {
        if (draw)
        {
            var pos = Mouse.GetPosition(imageCanvas);
            Rectangle rec = new Rectangle()
                    {
                        Width = 10,
                        Height = 10,
                        Fill = Brushes.Red,
                    };
            Canvas.SetTop(rec, pos.Y);
            Canvas.SetLeft(rec, pos.X);
            imageCanvas.Children.Add(rec);
        }

    }

我能做的是以下内容: https://www.dropbox.com/s/7moq4p8f8f409b3/wpf_canvas.png

为什么当光标位于画布之外时会调用StackPan_MouseMove?

这是可执行文件,您可以在其中注意到此行为: https://www.dropbox.com/s/ye1w2j9chld2oif/WpfApplication1.exe

2 个答案:

答案 0 :(得分:1)

您可以通过画布的矩形子项获取MouseMove事件。

虽然你应该更好地使用InkPresenter或InkCanvas(正如用户keyboardP所说的那样),你可以简单地使矩形不可见以进行测试。然后他们将不再产生任何输入事件。

Rectangle rec = new Rectangle()
{
    Width = 10,
    Height = 10,
    Fill = Brushes.Red,
    IsHitTestVisible = false // here
};

答案 1 :(得分:1)

尝试将Canvas放置在Border控件中,并将Border控件的ClipToBounds属性设置为true

<Border ClipToBounds="true" Grid.Row="1" Grid.Column="1" >
    <Canvas Name="imageCanvas" MouseEnter="StackPanel_MouseEnter" MouseLeave="StackPanel_MouseLeave" Background="LightGray" 
            MouseDown="StackPan_MouseDown" MouseUp="StackPan_MouseUp" MouseMove="StackPan_MouseMove">
    </Canvas>
</Border>

稍微不同的是,似乎InkPresenter / InkCanvas可能更适合您正在尝试的操作,除非您出于特定原因而避开它们。 / p>