VB.NET 如何动态添加组件,如FileSystemWatcher,并且响应同一事件?

VB.NET 如何动态添加组件,如FileSystemWatcher,并且响应同一事件?,第1张

For Each i In My.Computer.FileSystem.Drives

Dim FSW As New FileSystemWatcher

FSW.NotifyFilter = NotifyFilters.FileName

FSW.Path = i.Name.ToString

FSW.Filter = "*.txt"

AddHandler FSW.Changed, AddressOf FileSystemWatcher1_Changed '与FileSystemWatcher1_Changed事件绑定,以下同。

AddHandler FSW.Created, AddressOf FileSystemWatcher1_Created

AddHandler FSW.Deleted, AddressOf FileSystemWatcher1_Deleted

AddHandler FSW.Disposed, AddressOf FileSystemWatcher1_Disposed

AddHandler FSW.Error, AddressOf FileSystemWatcher1_Error

AddHandler FSW.Renamed, AddressOf FileSystemWatcher1_Renamed

FSW.EnableRaisingEvents = True

Next

上面代码放到一个调用过程中

Private Sub FileSystemWatcher1_Created(sender As Object, e As FileSystemEventArgs) Handles FileSystemWatcher1.Created

‘我用fsw的path属性区别多个分区,你用自己的代码就行,如果你没有创建FileSystemWatcher1,就把Handles FileSystemWatcher1.Created删除。

If sender.path = "C:\" Then

'代码

ElseIf sender.path = "D:\" Then

'代码

ElseIf sender.path = "F:\" Then

ElseIf sender.path = "H:\" Then

'……

End If

End Sub

自己在窗体上加一个按钮,以下是详细代码(整个类)

Public Class Form1

Private N As Integer '用来记添加要加入textbox的个数

Private PL As Integer = 10 'textbox相对于窗体的Left

Private PT As Integer = 10 'textbox相对于窗体的Top

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

Me.AutoScroll = True '窗体自动显示滚动条

N = 10 '初始化N为10

For i = 1 To N

Dim newtextbox As New TextBox

newtextbox.Left = PL

newtextbox.Top = PT

Me.Controls.Add(newtextbox)

PT += newtextbox.Height + 10 '各 newtextbox上下间隔10-------PL不变是希望左对齐

Next

End Sub

End Class

你还要把过程与控件事件绑定

AddHandler 控件.事件名,addressof 事件过程

RemoveHandler 这个是取消绑定

没发现自动生存的事件过程后面还有一个Hander button1.Click之类的,这就是所谓事件句柄。反而跟过程名没关系,改成阿猫阿狗也可以。

例外也可以像 Private WithEvents obj as ControlClass 这么声明控件变量,估计像vb6那样会在下拉列表中列出事件系列。

哎呀,说了半天跑题了。 ff不存在嘛多半不是它的作用域范围内,应该把ff变量定义在类中,而不是类中的某个过程中。

最好把代码添多一点,把ff部分也添出来看看。


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/bake/11955911.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-19
下一篇 2023-05-19

发表评论

登录后才能评论

评论列表(0条)

保存