Monday, December 29, 2008

How to Expose the Events of a Custom Control in the Parent Form

Say you have a custom control which has a PictureBox.  And you drop this control on a form.  But you want to be able to Code the MouseDown, MouseMove, MouseUp and Paint event of the PictureBox control that is on your custom control, and you want to code those events in the Form, not the control  You still with me?  You also don't want to create another control that inherits from your custom control to do this.  How can you do this?

There are actually a number of ways to do this.  Below are three ways:

1.  The easiest way to do this is to just raise an event in the Custom Control and handle that event in the Form.
      Public Event LinkClicked(ByVal sender As Object, ByVal e As EventArgs)
       Private Sub LinkLabel1_LinkClicked(ByVal sender As Object, ByVal e As System.Windows.Forms.LinkLabelLinkClickedEventArgs) Handles LinkLabel1.LinkClicked
              RaiseEvent LinkClicked(sender, e)
       End Sub

2.  Another way is to have a PictureBox value in the form point to the PictureBox that is on the control.  And then address the Mouse events there.  You'll need a way to return the Control to you via a FindControl routine in your Custom Control

  Public Function FindControl(ByVal Name As String) As Control
    For Each c As Control In Me.Controls
      If c.Name.ToLower = Name.ToLower Then
        Return c
      End If
    Next
  End Function

Then in your Form you would do the following:

  WithEvents MyFullImage As PictureBox

And in your Form_Load event:
    MyFullImage = ImgEditor1.FindControl("FullImage") 'This is assuming the FullImage is the name of the Picturebox in your Control

And then you can do the following:
  Private Sub MyFullImage_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles MyFullImage.MouseDown

  End Sub


3.  Lastly you would still use the FindControl mentioned in method 2, but do the following

      'Add this to form_load
      Dim pctBox as PictureBox = MyUserControl1.FindControl("FullImage")
      AddHandler  pctBox.Click, AddressOf TestClick


      Private Sub TestClick(ByVal sender As Object, ByVal e As System.EventArgs)
              MsgBox("Testing AddHandler Method")
          End Sub









No comments: