VB.net交叉形式跨线程表单调用?

时间:2015-05-23 14:08:00

标签: vb.net

我正在开发一个项目,该项目需要一个单独的表单来运行服务器线程来访问和更改另一个表单控件位置。我知道如何从另一个运行在同一表单上的线程调用一个控件,但我不知道如何在一个单独的表单和线程上执行它。

1 个答案:

答案 0 :(得分:2)

这是一个简单的例子......

在服务器表单中定义事件,并在适当时将其引发:

Public Class frmServer

    Public Event NewPosition(ByVal pt As Point)

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        ' ... in response to something (probably not a button click!) ...
        Dim x As Integer = 250
        Dim y As Integer = 100
        RaiseEvent NewPosition(New Point(x, y))
    End Sub

End Class

在主窗体中,在创建服务器窗体的实例时订阅该事件。可以使用AddHandler语句和AddressOf关键字来完成此操作。然后执行正常的Invoke模式以确保它在正确的UI线程中运行:

Public Class frmMain

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim server As New frmServer
        AddHandler server.NewPosition, AddressOf server_NewPosition
        server.Show()
    End Sub

    Private Delegate Sub dlgNewPosition(ByVal pt As Point)

    Private Sub server_NewPosition(pt As Point)
        If Me.InvokeRequired Then
            Me.Invoke(New dlgNewPosition(AddressOf server_NewPosition), New Object() {pt})
        Else
            Me.Location = pt
        End If
    End Sub

End Class