本例实现了一个鼠标控制控件移动的简单例子,配合鼠标捕获达成预想效果:

    1.新建一个wpf应用程序,为了演示效果,xaml简单修改如下:

    1. <Window x:Class="WpfApplication46.MainWindow"
    2. xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    3. xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    4. Title="MainWindow" Height="350" Width="525">
    5. <Canvas x:Name="LayoutRoot"
    6. MouseLeftButtonDown="LayoutRoot_MouseLeftButtonDown"
    7. MouseLeftButtonUp="LayoutRoot_MouseLeftButtonUp"
    8. MouseMove="LayoutRoot_MouseMove">
    9. <Ellipse Canvas.Left="30" Canvas.Top="30" Width="50" Height="50" Fill="Blue" />
    10. <Ellipse Canvas.Left="100" Canvas.Top="100" Width="70" Height="70" Fill="Green" />
    11. <Ellipse Canvas.Left="200" Canvas.Top="30" Width="90" Height="90" Fill="Yellow" />
    12. </Canvas>
    13. </Window>

    共有三个圆(蓝、绿、黄),下面将要实现如何用鼠标拖动他们移动


    2.后台cs如下:

    1. /// <summary>
    2. /// MainWindow.xaml 的交互逻辑
    3. /// </summary>
    4. public partial class MainWindow : Window
    5. {
    6. public MainWindow()
    7. {
    8. InitializeComponent();
    9. }
    10. Point pBefore = new Point();//鼠标点击前坐标
    11. Point eBefore = new Point();//圆移动前坐标
    12. bool isMove = false;//是否需要移动
    13. //Root 鼠标左键按下事件
    14. private void LayoutRoot_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    15. {
    16. if (e.OriginalSource.GetType() == typeof(Ellipse))
    17. {
    18. this.pBefore = e.GetPosition(null);//获取点击前鼠标坐标
    19. Ellipse el = (Ellipse)e.OriginalSource;
    20. this.eBefore = new Point(Canvas.GetLeft(el), Canvas.GetTop(el));//获取点击前圆的坐标
    21. isMove = true;//开始移动了
    22. el.CaptureMouse();//鼠标捕获此圆
    23. }
    24. }
    25. //Root 鼠标左键放开事件
    26. private void LayoutRoot_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
    27. {
    28. if (e.OriginalSource.GetType() == typeof(Ellipse))
    29. {
    30. Ellipse el = (Ellipse)e.OriginalSource;
    31. isMove = false;//结束移动了
    32. el.ReleaseMouseCapture();//鼠标释放此圆
    33. }
    34. }
    35. //Root 鼠标移动事件
    36. private void LayoutRoot_MouseMove(object sender, MouseEventArgs e)
    37. {
    38. if (e.OriginalSource != null && e.OriginalSource.GetType() == typeof(Ellipse) && isMove)
    39. {
    40. Ellipse el = (Ellipse)e.OriginalSource;
    41. Point p = e.GetPosition(null);//获取鼠标移动中的坐标
    42. Canvas.SetLeft(el, eBefore.X + (p.X - pBefore.X));
    43. Canvas.SetTop(el, eBefore.Y + (p.Y - pBefore.Y));
    44. }
    45. }
    46. }

    因为不知道鼠标将会点击圆的哪一个部位,所以需要计算鼠标坐标pBefore,设置圆的坐标eBefore;
    这里在鼠标左键按下点击圆的时候,设置了CaptureMouse,在鼠标松开左键时,设置ReleaseMouseCapture,试着注释掉这两行,观察程序运行的不同效果:

    (1).移动其中一个圆,当碰到其他圆的时候:
    设置了鼠标捕获的,移动中的圆将穿过其他圆而不造成影响;
    没有设置鼠标捕获的,移动中的圆,碰到其他圆的时候,将会发生跳跃,变成移动其他的圆;

    (2).移动圆至窗口边缘,甚至是窗口之外:
    设置了鼠标捕获的,圆可以被移动到窗口之外;
    没有设置鼠标捕获的,圆将被束缚在窗口之内;
    可以试着只保留CaptureMouse,而注释掉ReleaseMouseCapture,鼠标在捕获圆之后将无法释放,你甚至将无法点击窗口左上角的关闭按钮;
    鼠标捕获与释放CaptureMouse与ReleaseMouseCapture,在一些鼠标与控件的交互处理上将会体现出很大的作用,因为在你捕获一个控件时,鼠标将无法再操作到其他控件,同时也不会受其他控件的影响