2017-03-14 17 views
1

私はVBの新機能です。次のコードでこのエラーが発生します。PictureBoxのMouseDownエラー:Handles句にWithEventsが必要です

Handles句には、包含型またはその基本型のいずれかで定義されたWithEvents変数が必要です。 (BC30506)基本的に

Private Sub PictureBox1_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles PictureBox1.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 

ごとにマウスダウンイベントにピクチャボックスオブジェクトを移動しようとしていますコードが機能していません。

+2

あなたはコードでPictureBoxを作成しましたか? – Plutonix

答えて

0

あなたは設計者が作成したすべてのコントロールのようなFriend WithEventsとしてPictureBox1を宣言する必要があなたのコードを使用するには:

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 
+0

これはうまく機能しますが、私はこれを概念的に把握していません。 –

+0

にいくつかの説明とmsdnへのリンクが追加されました。 – tezzo

関連する問題