问题描述
非常简单的案例.
触发 MsgBox 的按钮内的表单类
Very simple case.
A Form Class inside a Button that triggers a MsgBox
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
MessageBox.Show("TEST")
End Sub
End Class
然后我创建一个新类 Class1 并将 Sub Button1_Click 移动到该类
then I create a new class Class1 and move the Sub Button1_Click to that class
Public Class Form1
End Class
Public Class Class1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Form1.Button1.Click
MessageBox.Show("TEST")
End Sub
End Class
我失败了
失败 BC30506 句柄子句需要在包含类型或其基类型之一中定义的 WithEvents 变量.
然后我是这样修改的:
Public Class Class1
Public WithEvents Form1.Button As EventThrower()
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Form1.Button1.Click
MessageBox.Show("TEST")
End Sub
End Class
现在我有 2 次失败
错误 BC30412 'WithEvents' 变量必须有一个 as 子句.
错误 BC31412 类中的句柄"必须指定一个 WithEvents 变量,使用单个标识符限定的MyBase"、MyClass"或Me".
Error BC31412 'Handles' in classes must specify a WithEvents variable, 'MyBase', 'MyClass' or 'Me' qualified with a single identifier.
有人能简单解释一下吗?
Can Somebody explain me this in a simple way ?
更新 1:
来自 Visual Vincent 的解决方案消除了错误,但通过单击 Form1 上的 Button1,MessageBox 不会被触发,因此实际上它不起作用.
UPDATE 1:
The Solution coming from Visual Vincent removes the Error but by clicking the Button1 on Form1 the MessageBox gets not fired, so practically its not working.
Public Class Class1
Public WithEvents Button1 As Button = Form1.Button1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
MessageBox.Show("TEST")
End Sub
End Class
如何从 Class1 中触发 Form1 上的 Button1?
How can I get the Button1 on Form1 fired from within the Class1 ?
推荐答案
试试这个:
Public Class Form1
'Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
' MessageBox.Show("TEST")
'End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
AddHandler Button1.Click, AddressOf Class1.ButtonClick
End Sub
End Class
Public Class Class1
Public Shared Sub ButtonClick(sender As Object, e As EventArgs)
MessageBox.Show("Clicked from ButtonClick")
End Sub
End Class
这篇关于奇怪的事情的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!