VBGood网站全文搜索 Google

搜索VBGood全站网页(全文搜索)
首页 - 经验之谈 - 让所有的控件都动起来
发表评论(0)作者:马致明, 平台:VB6.0+Win98, 阅读:9863, 日期:2000-11-01
让所有的控件都动起来
2000-10-27 14:49:15 马致明

--------------------------------------------------------------------------------


问题的提出
在各类应用程序中,除了窗体、消息框等极少数对象可以拖动外,其他控件因不具备Moveable属性而不能移动。但在程序运行期间,某些设置了AutoSize属性的控件(如图片框、标签等)会有损界面的美观性、合理性,这时我们很希望把它们挪个位置,以使界面更完美。如何实现这一要求呢?笔者经过思考和实践,找到了一种非常简捷的方法,此方法既适用于VB、VC++、VFP等Visual Studio系列,同样也适用于Delphi等编程工具。现将其介绍给各位编程爱好者,以便对你的开发工作有所启示。
编程思路
要使某个控件能够移动,首先其拖动属性(DragMode)必须设置成手动(Manual),而不能采用默认设置(自动:Automatic),否则控件拖动后又会蹦回原来的位置。其次,在该控件的MouseDown事件中,用全局变量OldX和OldY记录下鼠标按下时的位置,并使全局布尔型变量Down设为True(标志鼠标被按下)。然后,在该控件的MouseMove事件中,如果Down为True,则使该控件的左边界在原来的基础上加上水平方向的移动量(X-OldX),上边界在原来的基础上加上垂直方向的移动量(Y-OldY)。最后,在MouseUp事件中,使Down变为False(标志鼠标器已松开)。添加了这三个事件过程后,在程序运行时,该控件你想拖到哪儿均可,你甚至可以把它从窗体的边界拖出去(此后,你不会再看到它)。
实例程序(VB代码)
窗体上的控件:一个图片框,取名为Pic;一个标签,取名为 Lab;一个命令按钮,取名为Cmd。
Dim OldX As Integer, OldY As Integer, Down As Boolean
′移动命令钮
Sub Cmd-MouseDown(Button As Integer, Shift As Integer, X As Single, Y As Single)
OldX = X: OldY = Y
Down = True
End Sub
Sub Cmd-MouseMove(Button As Integer, Shift As Integer, X As Single, Y As Single)
If Down Then
Cmd.Left = Cmd.Left+X-OldX
Cmd.Top = Cmd.Top+Y-OldY
End If
End Sub
Sub Cmd-MouseUp(Button As Integer, Shift As Integer, X As Single, Y As Single)
Down = False
End Sub
′移动标签
Sub Lab-MouseDown(Button As Integer, Shift As Integer, X As Single, Y As Single)
OldX = X: OldY = Y
Down = True
End Sub
Sub Lab-MouseMove(Button As Integer, Shift As Integer, X As Single, Y As Single)
If Down Then
Lab.Left = Lab.Left+X-OldX
Lab.Top = Lab.Top+Y-OldY
End If
End Sub
Sub Lab-MouseUp(Button As Integer, Shift As Integer, X As Single, Y As Single)
Down = False
End Sub
′移动图片框
Sub Pic-MouseDown(Button As Integer, Shift As Integer, X As Single, Y As Single)
OldX = X: OldY = Y
Down = True
End Sub
Sub Pic-MouseMove(Button As Integer, Shift As Integer, X As Single, Y As Single)
If Down Then
Pic.Left = Pic.Left + X-OldX
Pic.Top = Pic.Top + Y-OldY
End If
End Sub
Sub Pic-MouseUp(Button As Integer, Shift As Integer, X As Single, Y As Single)
Down = False
End Sub