Thursday, December 27, 2007

sender or eventSender object, what is the point?

When looking at the MouseMove problem, I wandered over to the first argument passed to MouseMove, MouseDown, etc.

sender as System.Object (sometimes referred to as eventSender as System.Object).

What was the point of this this?  We never used it in our code, so why was it being passed?

From this article - http://www.informit.com/articles/article.aspx?p=102148&seqNum=3 I realized that you can use that argument to figure out the who called the function.  For example, if you have the MouseDown handle the call from 10 buttons, you can use the sender object to figure which button called the MouseDown routine.  What you need to do is convert (cast) it to an Control or a Button, and then you can get the Button's text.

Another use I found for this is if you manually call MouseDown, or manually call MouseMove.  In that past if we called a MouseMove event from the MouseDown routine, we just passed the sender from MouseDown to MouseMove.  Sample code below:

    Private Sub Form1_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles MyBase.MouseDown
        Form1_MouseMove(sender, e)
    End Sub

At first I thought in MouseMove, we could use the sender object to see if the routine was called by code or by the Form.  But in MouseMove, when you look at the sender object, you cannot tell.  So one way to tell is do something like this:

    Private Sub Form1_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles MyBase.MouseDown
        Form1_MouseMove("FromMouseDown", e)
    End Sub

Then in MouseMove, you can do the following:
    Private Sub Form1_MouseMove(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles MyBase.MouseMove
        If TypeOf sender Is String Then
          'Do Something, you can even test what the string value is
          Dim aString as String = DirectCast(sender, String)
             If aString = "FromMouseDown" Then
                MsgBox("FromMouseDown")
             End If
        End If
    End Sub



No comments: