首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >图片框上的MouseDown错误: Handles子句需要WithEvents

图片框上的MouseDown错误: Handles子句需要WithEvents
EN

Stack Overflow用户
提问于 2017-03-15 00:20:02
回答 1查看 110关注 0票数 1

我是VB的新手--在下面的代码中,我得到了这个错误。

Handles子句需要在包含类型或其基类型之一中定义的WithEvents变量。(BC30506)

代码语言:javascript
复制
Private Sub PictureBox1_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles PictureBox1.MouseDown

基本上,我正在尝试移动一个带有mousedown事件的图片框对象,就像这段代码一样

代码语言:javascript
复制
  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

我已经读过其他问题了,似乎不能准确地理解为什么这段代码不能工作。

EN

回答 1

Stack Overflow用户

发布于 2017-03-15 00:50:43

为了使用您的代码,您需要将PictureBox1声明为Friend WithEvents,就像设计器创建的每个控件一样:

代码语言:javascript
复制
Friend WithEvents PictureBox1

但是您只能在模块、接口或名称空间级别使用Friend。因此,Friend元素的声明上下文必须是源文件、名称空间、接口、模块、类或结构;不能是过程。

如果无法在运行时使用此声明创建控件,则必须使用AddHandler将事件与事件处理程序相关联。

例如:

代码语言:javascript
复制
AddHandler Me.PictureBox1.MouseDown, AddressOf PictureBox1_MouseDown
AddHandler Me.PictureBox1.MouseMove, AddressOf PictureBox1_MouseMove

您还必须从过程声明中删除Handles;即:

代码语言:javascript
复制
Private Sub PictureBox1_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs)
    'your code here
End Sub

提示:如果需要,可以为事件处理程序使用更好的名称,而不是默认名称;例如:

代码语言:javascript
复制
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
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42791248

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档