private withevents ctlTest as new panel
private mptEmpty as point=new point(-1,-1)
private stPoint as point = mpempty
private sub yourfrm_load(s as object,e as eventargs) handles mybase.load
ctrTest.size=new size(100,100)
ctrtest.location=new point(10,10)
ctl.borderstyle=borderstyle. fixedsingle
me.controls.add(ctltest)
end sub
private sub ctlTest_mousedown(s as obj,e as mseve)handles ctltest.mousedown
if e.button=mousebuttons.left then
stPoint=e.location
end if
end sub
private sub ctrtest_mouseUP(s as obj,e as mseve) handels ctrtest.MouseUp
stpoint=mptEmpty
end sub
private sub ctlTest_mousemove(s ....,e....) handles ctrtext.MouseMove
if stPoint<>mptEmpty then
ctltest.location +=e.location-stpoint
end if
end sub
先在左键按下时设置一个标志,我们同时用这个标志表示按下时的位置,然后只要计算现在鼠标位置和按下位置差值就知道移动多少,这样比移动过程中记录上次位置和当前位置要更准确,代码更简洁。鼠标抬起时就恢复这个标志,需要注意的是可能鼠标点到控件左上角0,0,所以标志自定义为-1,-1.移动时判断标志合法就进行移动控件就可以了。