gpt4 book ai didi

C#/WPF - 每帧调用方法

转载 作者:行者123 更新时间:2023-11-30 23:05:51 26 4
gpt4 key购买 nike

TL;DR:我想在每一帧调用一个方法。

我正在两个对象之间创建连接(用曲线表示)。

Drag a line between two objects.红色轮廓的矩形是我的别针。他们可以判断拖动操作何时开始和结束。不幸的是,当光标移到外面时,他们无法接收到 PreviewMouseMove 事件。但我希望能够在拖动时更新连接端点。

MyPin.cs:

private void MyPin_PreviewMouseDown(object sender, MouseButtonEventArgs e)
{
if (e.RightButton == MouseButtonState.Pressed)
return;
Connection.isDragging = true;
e.Handled = true;
}

private void MyPin_PreviewMouseUp(object sender, MouseButtonEventArgs e)
{
if (isDragging)
{
Connection.isDragging = false;
e.Handled = true;
}
}

因此,我使用 Canvas 的 PreviewMouseMove 事件解决了这个问题。

MyCanvas.cs

    private void Canvas_PreviewMouseMove(object sender, MouseEventArgs e)
{
if (DraggableElement.isDragging)
{
return;
}
else if(Connection.isDragging)
{
Connection.Preview.DragToMouse();
e.Handled = true;
}
// a bunch of other else if...
}

然而,随着项目规模的增长,像这样的变通办法变得难以维护。我确实有更好的解决方案,但我不知道如何实现。我想在 MyPin.cs 类中做一个更新函数:

private void MyPin_Tick()
{
// Called every frame, do drag logic here.
}

但是我怎样才能让这个方法在每一帧都被调用呢?

最佳答案

您需要做的就是使用 Mouse.Capture 捕获鼠标。一旦控件捕获鼠标,它将继续接收鼠标事件,即使鼠标退出控件也是如此。

private void MyPin_PreviewMouseDown(object sender, MouseButtonEventArgs e)
{
if (e.RightButton == MouseButtonState.Pressed)
return;
Connection.isDragging = true;
e.Handled = true;
Mouse.Capture((IInputElement)sender);
}

private void MyPin_PreviewMouseUp(object sender, MouseButtonEventArgs e)
{
if (isDragging)
{
Connection.isDragging = false;
e.Handled = true;
Mouse.Capture(null);
}
}

关于C#/WPF - 每帧调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48552784/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com