允许最终用户移动控件
我找到了一个很好的示例 这里,但我有一些问题。 1. 由于控件太大,没有将控件放置到鼠标离开的正确位置。
- 它可以被推出屏幕。我希望它应该保持在屏幕边界内。
这是我的代码:
Public Sub Form1_MouseMove(ByVal sender As Object, ByVal e As MouseEventArgs) Handles MyControl.MouseMove
If Not _capturingMoves Then
Return
End If
X = e.X
Y = e.Y
End Sub
Public Sub Form1_MouseUp(ByVal sender As Object, ByVal e As MouseEventArgs) Handles MyControl.MouseUp
If _capturingMoves Then
' Do any final placement
MyControl.Location = New Point(X, Y)
_capturingMoves = False
End If
End Sub
I found a good sample Here, but I have a few problems with it.
1. It is not placing the control to the correct position where the mouse left off becase the control is a big one.
- It could be pushed out of the screen.. I want it should stay within the screen boundaries.
This is my code:
Public Sub Form1_MouseMove(ByVal sender As Object, ByVal e As MouseEventArgs) Handles MyControl.MouseMove
If Not _capturingMoves Then
Return
End If
X = e.X
Y = e.Y
End Sub
Public Sub Form1_MouseUp(ByVal sender As Object, ByVal e As MouseEventArgs) Handles MyControl.MouseUp
If _capturingMoves Then
' Do any final placement
MyControl.Location = New Point(X, Y)
_capturingMoves = False
End If
End Sub
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我写了这样的东西来在网页上拖动div...
一般方法是保存 mousedown 上的坐标,获取 mouseup 上的坐标,然后根据差异移动对象的位置。
下面是一些示例代码:
我创建了一个
DragInfo
类,用于保留初始鼠标坐标和初始位置。然后,我在 mousedown 事件上将其中一个存储在控件的Tag
中:我的测试控件只是我从工具箱中放入的一个面板。我猜它可能是任何东西。以下是面板 (
Panel1
) 的 mousedown、mousemove 和 mouseup 事件处理程序:就是这样!那行得通。请注意,mousemove 方法检查控件是否位于窗体的 clientrectangle 内。
或者,一种更通用的方法:
现在您可以使用
MakeDraggable(Panel1)
或任何其他控件来使其可拖动!编辑:两个示例现在都可以防止控件被拖出边界。
I wrote something like this for dragging divs on a webpage...
The general approach was to save the coordinates on mousedown, get the coordinates on mouseup, and shift the object's location by the difference.
Here's some example code:
I made a
DragInfo
class that keeps the initial mouse coords and initial location. I then store one of these guys in the control'sTag
on the mousedown event:My test control is just a panel that I put from the toolbox. It could be anything I guess. Here are my mousedown, mousemove, and mouseup event handlers for the panel (
Panel1
):There you go! That works. Note that the mousemove method checks if the control is within the form's clientrectangle.
Or, a more generic way to go:
Now you can just use
MakeDraggable(Panel1)
or any other control to make it draggable!Edit: Both examples now keep the control from being dragged out of bounds.