[visual-studio].Net WindowsForms MouseDown 事件不触发

发布时间: 2014/3/1 4:57:10
注意事项: 本文中文内容可能为机器翻译,如要查看英文原文请点击上面连接.

作为新用户到 VB,我竭力要看看这段代码为什么工作在一个项目中但不是在另一种。如果创建一个新的项目和 2 新形式,但当我将我的项目中时,它不在所有开火或是离开或右键单击此代码工作正常。

我试过的 try/catch 语句,但是未被报告任何错误。如何着手进行故障排除时,找出错误。我试着给出代码 rem,但仍然相同每个注释后运行。我甚至试图删除离开只是但没有喜悦 2 潜艇在窗体上的所有其他代码。任何帮助非常感谢。

图像

Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load


        'TODO: This line of code loads data into the 'StorageDataSet1.Customers' table. You can move, or remove it, as needed.
        Me.CustomersTableAdapter.Fill(Me.StorageDataSet1.Customers)
        'TODO: This line of code loads data into the 'StorageDataSet.User' table. You can move, or remove it, as needed.
        Me.UserTableAdapter.Fill(Me.StorageDataSet.User)

        'Dim frmDepartmentsLive As New frmDepartment
        'frmDepartmentsLive.Owner = Me
        'frmDepartmentsLive.ShowDialog()


        lblDate.Text = Now

        Timer1.Start()

        rdoCustomer.Enabled = False
        rdoCustomer.Checked = True
        rdoDepartment.Enabled = False
        rdoDepartment.Checked = False

        For Each ctrl In Me.Controls
            If TypeOf ctrl Is Button Then
                AddHandler CType(ctrl, Button).MouseDown, AddressOf btn_MouseDown
            End If
        Next

    End Sub

Private Sub btn_MouseDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs)

        If (e.Button = MouseButtons.Right) Then
            Dim btn = CType(sender, Button)
            frmRacks.buttonName = btn.Name.Replace("btn", "")
            frmRacks.Show()
        ElseIf (e.Button = MouseButtons.Left) Then
            MessageBox.Show("To be coded")
        End If
    End Sub

frmRacks

Public Class frmRacks
    Public buttonName As String
    Private Sub racksfrm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        lblRacks.Text = buttonName

    End Sub

    Private Sub btnCancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCancel.Click
        Me.Close()
    End Sub



End Class

解决方法 1:

由于控件在面板上,他们是该面板控件数组的不是形式的成员。这 — — 和其他的东西 — — 是明显的如果你看通过窗体的设计器 (在解决方案资源管理器,请单击全部显示,然后打开 formXXX.designer.vb )。不要改变什么,但它演示如何创建并添加控件。所以...

    For Each ctrl In thepanelName.Controls
        If TypeOf ctrl Is Button Then
            AddHandler CType(ctrl, Button).MouseDown, AddressOf btn_MouseDown
        End If
    Next

如果是只有那些面板上的按钮可以简单地把它切:

  For Each btn As Button In thepanelName.Controls
       AddHandler CType(ctrl, Button).MouseDown, AddressOf btn_MouseDown
  Next
赞助商