单击表单会导致 'Unable to cast object of type '<Namespace.FormName>' 键入 'System.Windows.Forms.Button'

Clicking on the form causes 'Unable to cast object of type '<Namespace.FormName>' to type 'System.Windows.Forms.Button'

我正在制作 Microsoft 游戏的一个版本 'Minesweeper'。我以编程方式制作按钮和标签,并为按钮添加两个处理程序,为标签添加一个处理程序,如下所示。

AddHandler Newbtn.MouseDown, AddressOf Button_MouseDown
AddHandler Newbtn.MouseUp, AddressOf Button_MouseUp
AddHandler Newlbl.MouseDown, AddressOf Label_MouseDown

那我有三个程序:

Private Sub Button_MouseUp(sender As Button, e As MouseEventArgs) Handles Me.MouseUp
 Private Sub Button_MouseDown(sender As Button, e As MouseEventArgs) Handles Me.MouseDown
Private Sub Label_MouseDown(sender As Label, e As MouseEventArgs) Handles Me.MouseClick

一切正常,直到我在表单本身的按钮网格之外单击,然后我得到 'invalidcastexception'。 VS2015 进入中断状态。在顶部它说:

"Your Application has entered a break state, but there is no code to show because all threads were executing external code(typically system or framework code)."

附加信息:无法将类型 'Mines.MineSweeperPJS' 的对象转换为类型 'System.Windows.Forms.Button'。

Mines 是命名空间。 MineSweeperPJS 是表单。

如能就此问题的原因提出任何建议,我们将不胜感激!

问题出在你的事件处理程序的这一部分

..... Handles Me.MouseUp
             ^^^

这意味着表单 (Me) 上的每个 mouseup 或 mousedown 事件都会传递给指定的事件处理程序。
我认为您已经手动编写了此事件处理程序,将参数 sender 从对象更改为按钮,因为如果您让表单设计器使用它自己的模板,您最终会得到类似这样的东西

Private Sub Button_MouseUp(sender As Object, e As MouseEventArgs) Handles Newbtn.MouseUp

当表单引擎调用这些事件处理程序时,为了响应表单 mousedown 或 mouseup,它传递对表单本身 (Me) 的引用,而不是对 Button 的引用。这就是无效转换的原因。

您可以删除 ...Handles Me.MouseUp,因为您已经使用 AddHandler 设置了事件处理程序,并将 sender 参数恢复为 As Object