Domanda

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 ?

È stato utile?

Soluzione

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

Altri suggerimenti

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)
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top