gpt4 book ai didi

在创建窗口句柄之前,无法在控件上调用 VB.NET Invoke,但句柄已创建

转载 作者:行者123 更新时间:2023-12-02 08:38:43 24 4
gpt4 key购买 nike

这是我的情况,有2个类和我的主表单Form1:

Class1:有一个方法 doSomethingAndCall(callback),它创建一个新线程Class2:具有动态创建的控件,带有触发 Class1.doSomethingAndCall(newCallback) 的按钮

在代码中它看起来像这样(它从 Class2.Button_Click 开始):

Class Class1
public shared sub doSomethingAndCallAsync(state as object)
Console.WriteLine(Form1.InvokeRequired) 'output: false
Console.WriteLine(Form1.IsHandleCreated) 'output: false
Form1.Invoke(state.callback) 'throws System.InvalidOperationException
end sub

public shared sub doSomethingAndCall(callback as object)
System.Threading.ThreadPool.QueueUserWorkItem(AddressOf doSomethingAndCallAsync, New With {.callback = callback})
end sub
End Class

Class Class2
Public Delegate Sub doSomethingDelegate()

Public Sub doSomething()
Console.WriteLine("success!")
End Sub

Public Sub Button_Click(ByVal sender As Object, ByVal e As System.EventArgs)
Class1.doSomethingAndCall(New doSomethingDelegate(AddressOf doSomething))
End Sub
End Class

我得到的确切异常是:

Invoke or BeginInvoke cannot be called on a control until the window handle has been created

正如我所看到的,第 4 行中的 console.WriteLine 向我显示该表单实际上并未创建。所以我添加了这个处理程序,现在它变得非常困惑:

 Private Sub Form1_HandleCreated(sender As Object, e As System.EventArgs) Handles Me.HandleCreated
Console.WriteLine("Handle created") 'Output: Handle created, when running program
End Sub

Private Sub Form1_HandleDestroyed(sender As Object, e As System.EventArgs) Handles Me.HandleDestroyed
Console.WriteLine("Handle destroyed") 'Will never Output!
End Sub

所以它被创建并且从未被销毁,但是如果我单击按钮它仍然不可用? -任何人都可以解释一下发生了什么以及如何正确调用回调,谢谢!

最佳答案

My.Forms.Form1 的实例。 Form1 在每个线程中都会有所不同。您需要正确实例的句柄。将按钮拖放到 Form1 上并添加以下代码:

Public Class Form1

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Threading.Tasks.Task.Factory.StartNew(Sub() Class1.Wrong())
Threading.Tasks.Task.Factory.StartNew(Sub() Class1.Correct(Me))
End Sub

End Class

Public Class Class1

Public Shared Sub Wrong()
Debug.WriteLine(String.Format("(Other thread, wrong) InvokeRequired={0}, IsHandleCreated={1}", Form1.InvokeRequired, Form1.IsHandleCreated))
End Sub

Public Shared Sub Correct(instance As Form1)
Debug.WriteLine(String.Format("(Other thread, correct) InvokeRequired={0}, IsHandleCreated={1}", instance.InvokeRequired, instance.IsHandleCreated))
End Sub

End Class

输出

(Other thread, correct) InvokeRequired=True, IsHandleCreated=True

(Other thread, wrong) InvokeRequired=False, IsHandleCreated=False

关于在创建窗口句柄之前,无法在控件上调用 VB.NET Invoke,但句柄已创建,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25644824/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com