C#WPF - DragMove窗口和Click事件

时间:2017-11-12 19:39:19

标签: c# wpf mouseevent

我正在构建一个无边框应用程序。我需要实现的是移动窗口,只需单击并拖动它包含的图像,但我也想在点击时执行某些操作。

this is how my app looks 只需一个按钮,我就可以实现左右点击功能,但无法确定如何实现拖动功能。 这就是我的代码看起来像

private void btnHome_MouseDown(object sender, MouseButtonEventArgs e)
    {
        if(e.LeftButton == MouseButtonState.Released)
        {
            toggle();
        }
        else if(e.LeftButton == MouseButtonState.Pressed)
        {
            DragMove();
        }
    }

现在只有拖动工作,如果我重新排列它们的出现,那么只有左键单击才有效。右键单击功能现在按预期工作。

2 个答案:

答案 0 :(得分:0)

编辑:我发现了问题!你听老鼠 Down 事件!!!!

只需将新事件链接到以下新功能=]

即可
private void btnHome_MouseUp(object sender, MouseButtonEventArgs e)
{
     toggle();
}

private void btnHome_MouseDown(object sender, MouseButtonEventArgs e)
{
    DragMove();
    RaiseEvent(new MouseButtonEventArgs(e.MouseDevice, e.Timestamp, MouseButton.Left) 
    { 
        RoutedEvent = MouseLeftButtonUpEvent 
    });
}

答案 1 :(得分:0)

一旦DragMove()方法返回,即释放鼠标捕获时,请执行操作:

private void btnHome_MouseDown(object sender, MouseButtonEventArgs e)
{
    if (e.LeftButton == MouseButtonState.Pressed)
    {
        DragMove();
        System.Diagnostics.Debug.Write("some action...");
    }
}

或者,如果您想在捕获鼠标之前执行某些操作,则可以使用布尔标记:

private bool _capture;
private void btnHome_MouseDown(object sender, MouseButtonEventArgs e)
{
    if (e.LeftButton == MouseButtonState.Pressed)
    {
        if (_capture)
        {
            DragMove();
            _capture = false;
        }
        else
        {
            System.Diagnostics.Debug.Write("some action...");

            _capture = true;
            btnHome.RaiseEvent(new MouseButtonEventArgs(e.MouseDevice, e.Timestamp, MouseButton.Left)
            {
                RoutedEvent = MouseDownEvent
            });
        }
    }
}