自定义控件错误的 AddHandler Visual Studio



我有一个 MouseEnter 事件,它当前处理窗体上的一些自定义控件。该程序是一个纸牌游戏。我有一个集合(手卡),当用户绘制卡片时填充,然后将最新的卡片添加到窗体中。此集合包含各种自定义类型的卡片,所有这些卡片都继承自图片框。从牌组中抽出卡片并将它们添加到表单中可以正常工作。我遇到的麻烦是,在运行时,在绘制卡片并将其添加到表单后,我创建了一个 addhandler 代码行,让这些卡片响应我的 MouseEnter 事件,但我的 addhandler 代码行告诉我 MouseEnter 不是对象的事件。如何解决此问题,以便在绘制卡片并将其添加到窗体后,当鼠标进入新的自定义控件时,将触发我的 MouseEnter 事件?这是我尝试过的众多方法之一,我认为应该是最简单和最简单的方法。

deck.DrawCard()
AddHandler handCards(handCards.Count).MouseEnter, AddressOf Cards_MouseEnter

附言 MouseEnter 事件适用于运行时之前位于窗体上的自定义控件,它所做的只是获取控件的图像,并通过将图像放置到窗体上的较大卡片来放大它。

我假设你的手卡集合是一个对象集合。尝试使用 CType 将其转换为正确的类型,如下所示:

AddHandler CType(handCards(handCards.Count), PictureBox).MouseEnter, AddressOf Cards_MouseEnter

正如@Jason提到的,使用 handCards.Count 作为索引将不起作用,因为它是项目总数,因为您的索引从零开始,并且将比 Count 少一个。所以handCards(handCard.Count)应该handCards(handCards.Count -1)

这就是我修复它的方式,以防有人遇到这篇文章。 做了一个单独的子来做AddHandler。程序抽卡后,它会调用此方法,然后添加我需要的 MouseEnter 处理程序。ByVal是关键。我最初认为我应该使用 ByRef,但没有。MouseEnter 是一个控制事件,但显然不是 Object,所以现在它可以工作了。

Public Sub addHandlers(ByVal inputObject As Control)
    AddHandler inputObject.MouseEnter, AddressOf Cards_MouseEnter
End Sub

可以使用泛型集合来避免类型强制转换。

Private handCards As System.Collections.Generic.List(Of PictureBox) _
    = New System.Collections.Generic.List(Of PictureBox)(52)

或者你可以只使用一个PictureBox对象的数组

Private handCards(5) As PictureBox

请记住,您必须通过为数组的每个元素分配一个PictureBox对象来初始化集合或数组。

现在,您可以将处理程序添加到数组的 PictureBox 元素中,因为PictureBox派生自实现 MouseEnter 事件的Control

deck.DrawCard()
If handCards.Count > 0 andAlso handCards.Last() IsNot Nothing then
    AddHandler handCards.Last().MouseEnter, AddressOf Cards_MouseEnter
End If

您的处理程序将如下所示

Private Function Cards_MouseEnter(sender As Object, e As System.EventArgs) As Object
    ' Handle mouse events here
End Function

幸运的是,我正在解决,并设法成功地完成了这个解决方案。

首先添加事件处理程序方法 随心所欲,为了测试,我在Button_Click添加了这个函数

addHandlers(Label1) 'Label one is the control on which I have to attach Mouse Events (Enter,LEave)

现在"addHandlers"函数实现

 Public Sub addHandlers(ByVal obj1 As Control)
    AddHandler obj1.MouseEnter, AddressOf MouseEventArgs
    AddHandler obj1.MouseLeave, AddressOf _MouseLeave
 End Sub

现在鼠标事件:

Private Function _MouseLeave(ByVal sender As Object, ByVal e As System.EventArgs) As Object
    Try
        Me.Cursor = Cursors.Default
    Catch ex As Exception
    End Try
End Function
Private Function MouseEventArgs(ByVal sender As Object, ByVal e As System.EventArgs) As Object
    Try
        Me.Cursor = Cursors.Hand
    Catch ex As Exception
    End Try
End Function

最新更新