I might be missing something obvious, but I'm not able to return a value with a delegate.
Private Delegate Sub ChangeTextDelegate(tb As TextBox)
Private Sub ChangeText(tb As TextBox)
If tb.InvokeRequired Then
tb.Invoke(New ChangeTextDelegate(AddressOf ChangeText), tb)
Else
tb.Text = "NEW TEXT"
End If
End Function
Sub Delegate works well.
Private Delegate Function TextLengthDelegate(tb As TextBox) As Integer
Private Function TextLength(tb As TextBox) As Integer
If tb.InvokeRequired Then
tb.Invoke(New TextLengthDelegate(AddressOf TextLength), tb)
Else
Return tb.TextLength
End If
End Function
But this Function Delegate doesn't seem to work since i == 0 after dim i = TextLength(myTextBox), even though tb.TextLength == 68
Any idea ?
You are not returning the value if the Invoke is required.
Try this instead:
Private Delegate Function TextLengthDelegate(tb As TextBox) As Integer
Private Function TextLength(tb As TextBox) As Integer
If tb.InvokeRequired Then
Return CInt(tb.Invoke(New TextLengthDelegate(AddressOf TextLength), tb))
Else
Return tb.TextLength
End If
End Function
However, you might find this code easier as you don't have to define a separate delegate:
Private Function TextLength(tb As TextBox) As Integer
If tb.InvokeRequired Then
Return CType(tb.Invoke(New Action(Of TextBox)(AddressOf TextLength), tb), Integer)
Else
Return tb.TextLength
End If
End Function
Doesn’t VS warn you about your code since it doesn’t return a value when invoking the delegate?
tb.Invoke(New TextLengthDelegate(AddressOf TextLength), tb)
You have to return the value returned by Invoke, and since Invoke returns an Object, you need to cast the value:
Dim result = tb.Invoke(New TextLengthDelegate(AddressOf TextLength), tb)
Return DirectCast(result, Integer)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With