处理在代码中创建的表单 (WinForms)
Handle form created in code (WinForms)
我运行陷入了一点问题。使用这段代码,我为文件夹中的每个“.jpg”文件创建了一个 new 表单:
Dim d As DirectoryInfo = New DirectoryInfo("path to folder")
For Each bild As FileInfo In d.GetFiles("*.jpg")
Dim p As New Form
p.Show()
Next
现在我在处理表单 (p) 事件时遇到了一些问题。我知道如何处理在代码中创建的表单,但如果创建了多个表单,这将不起作用。只有最后一个获得了事件。
AddHandler p.Click, AddressOf p_click()
简而言之:如何在代码中创建多个表单时每个表单都获取事件(p_click)?
Yes I'm calling AddHandler right before p.Show()
那是正确的...您在处理程序中转换 sender
参数以获取对表单的引用:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim d As DirectoryInfo = New DirectoryInfo(My.Computer.FileSystem.SpecialDirectories.MyPictures)
For Each bild As FileInfo In d.GetFiles("*.jpg")
Dim p As New Form
AddHandler p.Click, AddressOf p_Click
p.BackgroundImage = Image.FromFile(bild.FullName)
p.BackgroundImageLayout = ImageLayout.Zoom
p.Show()
Next
End Sub
Private Sub p_Click(sender As Object, e As EventArgs)
Dim frm As Form = DirectCast(sender, Form)
' ... do something with "frm" ...
frm.Close()
End Sub
我运行陷入了一点问题。使用这段代码,我为文件夹中的每个“.jpg”文件创建了一个 new 表单:
Dim d As DirectoryInfo = New DirectoryInfo("path to folder")
For Each bild As FileInfo In d.GetFiles("*.jpg")
Dim p As New Form
p.Show()
Next
现在我在处理表单 (p) 事件时遇到了一些问题。我知道如何处理在代码中创建的表单,但如果创建了多个表单,这将不起作用。只有最后一个获得了事件。
AddHandler p.Click, AddressOf p_click()
简而言之:如何在代码中创建多个表单时每个表单都获取事件(p_click)?
Yes I'm calling AddHandler right before p.Show()
那是正确的...您在处理程序中转换 sender
参数以获取对表单的引用:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim d As DirectoryInfo = New DirectoryInfo(My.Computer.FileSystem.SpecialDirectories.MyPictures)
For Each bild As FileInfo In d.GetFiles("*.jpg")
Dim p As New Form
AddHandler p.Click, AddressOf p_Click
p.BackgroundImage = Image.FromFile(bild.FullName)
p.BackgroundImageLayout = ImageLayout.Zoom
p.Show()
Next
End Sub
Private Sub p_Click(sender As Object, e As EventArgs)
Dim frm As Form = DirectCast(sender, Form)
' ... do something with "frm" ...
frm.Close()
End Sub