如何用鼠标在面板上移动控件

本文关键字:移动控件 何用 鼠标 | 更新日期: 2023-09-27 18:03:19

当鼠标不在边界控件中时,无法移动边界控件

<Window
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:WpfApplication2"
  x:Class="WpfApplication2.MainWindow"
  x:Name="Window"
  Title="Window1"
  Width="346.5" Height="215" WindowStyle="SingleBorderWindow" >
    <Grid Name="stack" >
        <Border x:Name="btn" Width="50" Height="20" VerticalAlignment="Top" BorderThickness="1" BorderBrush="Black" Background="#FFF50000"
                MouseMove="btn_MouseMove" MouseDown="btn_MouseDown" MouseUp="btn_MouseUp"  />
    </Grid>
</Window> 

背后的代码
bool state = false;
Point prePoint;
private void btn_MouseMove(object sender, MouseEventArgs e)
{
    if (state)
    {
        Point p = e.GetPosition(this);
        Point p2 = e.GetPosition(btn);
        btn.Margin = new Thickness(0, p.Y - p2.Y + p.Y - prePoint.Y, 0, 0);
        prePoint = e.GetPosition(this);
    }
}
private void btn_MouseDown(object sender, MouseButtonEventArgs e)
{
    if (sender == btn)
    {
        prePoint = e.GetPosition(this);
        state = true;
    }
}
private void btn_MouseUp(object sender, MouseButtonEventArgs e)
{
    state = false;
}

如何用鼠标在面板上移动控件

因为当鼠标处于边框控制中时,鼠标移动事件会触发。我认为你需要为窗口添加鼠标移动事件而不是边框控件

只要在鼠标进入边框时捕获鼠标,并在任务完成后释放鼠标,否则鼠标会粘住。或acc。在你的代码中,它可能像这样->

bool state = false;
Point prePoint;
private void btn_MouseMove(object sender, MouseEventArgs e)
{
if (state)
{
    Point p = e.GetPosition(this);
    Point p2 = e.GetPosition(btn);
    btn.Margin = new Thickness(0, p.Y - p2.Y + p.Y - prePoint.Y, 0, 0);
    prePoint = e.GetPosition(this);
    // Capture Mouse here ! as far as i think. !!!
    Mouse.Capture(this.ColorPlane, CaptureMode.Element);
}
else
{
    // Release Mouse here ! as far as i think. !!!
    Mouse.Capture(null);
}
}