Если вы вызываете MethodName для конструктора формы (новый) или в событии формы Load, ваш пример кода не будет работать. Возможно, поэтому он не работает для вас.
Конструктор Sub New. Вы должны быть осторожны с некоторыми инициализациями в конструкторе или событии Load формы. Причина в том, что дескриптор элемента управления, который включает форму, еще не создан. Если тестовый проект работает, то сравните тестовый проект с тем, что у вас есть. Подумайте, как вы вызываете методы и где. Наиболее вероятная причина того, что ваше приложение не работает, связана с тем, что обработчик не добавлен, потому что форма не создана. (Он создается, когда форма становится видимой. Вы можете попробовать добавить форму. Создайте элемент управления непосредственно перед добавлением обработчика.)
Кроме того, попробуйте добавить обработчик в форму через конструктор. Это гарантирует, что обработчик назначен правильно. (Пример MSDN делает все вручную, и это не очень хороший пример. Пример VB должен показать вам, как сделать это простым способом VB вместо более продвинутого ручного способа.)
Public Class Form1
Inherits System.Windows.Forms.Form
#Region " Designer-Generated "
'Form overrides dispose to clean up the component list.
<System.Diagnostics.DebuggerNonUserCode()> _
Protected Overrides Sub Dispose(ByVal disposing As Boolean)
Try
If disposing AndAlso components IsNot Nothing Then
components.Dispose()
End If
Finally
MyBase.Dispose(disposing)
End Try
End Sub
Friend WithEvents Button2 As System.Windows.Forms.Button
'Required by the Windows Form Designer
Private components As System.ComponentModel.IContainer
'NOTE: The following procedure is required by the Windows Form Designer
'It can be modified using the Windows Form Designer.
'Do not modify it using the code editor.
<System.Diagnostics.DebuggerStepThrough()> _
Private Sub InitializeComponent()
Me.Button1 = New System.Windows.Forms.Button
Me.Button2 = New System.Windows.Forms.Button
Me.SuspendLayout()
'
'Button1
'
Me.Button1.Location = New System.Drawing.Point(0, 0)
Me.Button1.Name = "Button1"
Me.Button1.Size = New System.Drawing.Size(75, 23)
Me.Button1.TabIndex = 0
Me.Button1.Text = "Button1"
Me.Button1.UseVisualStyleBackColor = True
'
'Button2
'
Me.Button2.Location = New System.Drawing.Point(0, 29)
Me.Button2.Name = "Button2"
Me.Button2.Size = New System.Drawing.Size(75, 23)
Me.Button2.TabIndex = 1
Me.Button2.Text = "Button2"
Me.Button2.UseVisualStyleBackColor = True
'
'Form1
'
Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!)
Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
Me.ClientSize = New System.Drawing.Size(292, 266)
Me.Controls.Add(Me.Button2)
Me.Controls.Add(Me.Button1)
Me.Name = "Form1"
Me.Text = "Form1"
Me.ResumeLayout(False)
End Sub
Friend WithEvents Button1 As System.Windows.Forms.Button
#End Region
Public Sub New()
' This call is required by the Windows Form Designer.
InitializeComponent()
' Add any initialization after the InitializeComponent() call.
MethodName() 'will not work here
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
MethodName() 'will not work here
'Me.CreateControl()
MethodName2() 'still will not work
End Sub
Private Function MethodName() As Boolean
AddHandler Me.HelpRequested, AddressOf Me.MsgBoxHelpRequested
Select Case MessageBox.Show("Text", "Title", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2, 0, True)
Case Windows.Forms.DialogResult.Yes
' Do stuff
Case Windows.Forms.DialogResult.No
' Do stuff
Case Windows.Forms.DialogResult.Cancel
RemoveHandler Me.HelpRequested, AddressOf Me.MsgBoxHelpRequested
Return False
End Select
RemoveHandler Me.HelpRequested, AddressOf Me.MsgBoxHelpRequested
End Function
Private Function MethodName2() As Boolean
AddHandler Me.HelpRequested, AddressOf Me.MsgBoxHelpRequested2
Select Case MessageBox.Show("Text", "Title", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2, 0, True)
Case Windows.Forms.DialogResult.Yes
' Do stuff
Case Windows.Forms.DialogResult.No
' Do stuff
Case Windows.Forms.DialogResult.Cancel
RemoveHandler Me.HelpRequested, AddressOf Me.MsgBoxHelpRequested2
Return False
End Select
RemoveHandler Me.HelpRequested, AddressOf Me.MsgBoxHelpRequested2
End Function
''' <summary>
''' AddHandler Me.HelpRequested, AddressOf Module1.MsgBoxHelpRequested3
''' </summary>
Private Function MethodName3() As Boolean
AddHandler Me.HelpRequested, AddressOf Module1.MsgBoxHelpRequested3
Select Case MessageBox.Show("Text", "Title", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button3, 0, True)
Case Windows.Forms.DialogResult.Yes
' Do stuff
Case Windows.Forms.DialogResult.No
' Do stuff
Case Windows.Forms.DialogResult.Cancel
RemoveHandler Me.HelpRequested, AddressOf Module1.MsgBoxHelpRequested3
Return False
End Select
RemoveHandler Me.HelpRequested, AddressOf Module1.MsgBoxHelpRequested3
End Function
Private Sub MsgBoxHelpRequested(ByVal sender As Object, ByVal hlpevent As System.Windows.Forms.HelpEventArgs)
' Breakpoint that never gets hit
MsgBox("Here I am to save the day!")
End Sub
Private Sub MsgBoxHelpRequested2(ByVal sender As Object, ByVal hlpevent As System.Windows.Forms.HelpEventArgs)
' Breakpoint that never gets hit
MsgBox("Shoot, still now working.")
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
MethodName() 'always works because all handles are created
End Sub
Private Sub Form1_HelpRequested(ByVal sender As System.Object, ByVal hlpevent As System.Windows.Forms.HelpEventArgs) Handles MyBase.HelpRequested
MsgBox("Always works! No need to add a handler because of Handles MyBase.HelpRequested.")
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
MethodName3()
End Sub
End Class
Module Module1
Public Sub MsgBoxHelpRequested3(ByVal sender As Object, ByVal hlpevent As System.Windows.Forms.HelpEventArgs)
MsgBox("Being handled in a module.")
End Sub
End Module