我是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我已经读过其他问题了,似乎不能准确地理解为什么这段代码不能工作。
发布于 2017-03-15 00:50:43
为了使用您的代码,您需要将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 Subhttps://stackoverflow.com/questions/42791248
复制相似问题