我是VB的新手 - 在下面的代码中我得到了这个错误。
Handles子句需要在包含类型或其基类型之一中定义的WithEvents变量。 (BC30506)
Private Sub PictureBox1_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles PictureBox1.MouseDown
基本上我正在尝试根据此片段移动带有mousedown事件的图片框对象
Private Offset As Size 'used to hold the distance of the mouse`s X and Y position to the picturebox Left and Top postition
Private Sub PictureBox1_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles PictureBox1.MouseDown
Dim ptc As Point = Me.PointToClient(MousePosition) 'get the mouse position in client coordinates
Offset.Width = ptc.X - PictureBox1.Left 'get the width distance of the mouse X position to the picturebox`s Left position
Offset.Height = ptc.Y - PictureBox1.Top 'get the height distance of the mouse Y position to the picturebox`s Top position
End Sub
Private Sub PictureBox1_MouseMove(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles PictureBox1.MouseMove
If e.Button = MouseButtons.Left Then 'make sure the left mouse button is down first
Dim ptc As Point = Me.PointToClient(MousePosition) 'get the mouse position in client coordinates
PictureBox1.Left = ptc.X - Offset.Width 'set the Left position of picturebox to the mouse position - the offset width distance
PictureBox1.Top = ptc.Y - Offset.Height 'set the Top position of picturebox to the mouse position - the offset height distance
End If
End Sub
我已经阅读了其他问题,似乎无法准确理解为什么这段代码无效。
答案 0 :(得分:0)
为了使用您的代码,您需要将PictureBox1
声明为Friend WithEvents
,就像设计师创建的每个控件一样:
Friend WithEvents PictureBox1
但您只能在模块,接口或命名空间级别使用Friend
。因此,Friend
元素的声明上下文必须是源文件,命名空间,接口,模块,类或结构;它不能成为一个程序。
如果您无法在运行时使用此声明创建控件,则必须使用AddHandler
将事件与事件处理程序相关联。
例如:
AddHandler Me.PictureBox1.MouseDown, AddressOf PictureBox1_MouseDown
AddHandler Me.PictureBox1.MouseMove, AddressOf PictureBox1_MouseMove
您还必须从过程声明中删除Handles
;即:
Private Sub PictureBox1_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs)
'your code here
End Sub
提示:如果您愿意,可以为事件处理程序使用更好的名称而不是默认名称;即:
AddHandler Me.PictureBox1.MouseMove, AddressOf movePictureBoxOnMouseLeftClick
Private Sub movePictureBoxOnMouseLeftClick(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs)
'your code here
End Sub