Control Finder Class
من فترة كنت كتبت بعص الأكواد لإيجاد جميع الكونترول الموجودة في اي كونترول
و الكود موجود في اللينك التالي
لكن و مع التطور الحاصل في الدوت نت قررت أخيرا تحويل معظم الأكواد الي كلاسات بحيث يسهل تطويرها و الاستفادة منها في اي مشروعات مستقبلة
و الكود التالي عبارة عن مساهمة جيدة يمكن إضافتها الي اي مكتبة يتم كتابتها للدوت نت
Public Class ControlFinder
Private _controls As IEnumerable(Of Control)
Public Sub New(ctrl As Control)
Me.New(ctrl, Function(c) c IsNot Nothing AndAlso Not c.IsDisposed AndAlso c.IsHandleCreated AndAlso c.Visible)
End Sub
Public Sub New(ctrl As Control, criteria As Func(Of Control, Boolean))
If ctrl Is Nothing Then
_controls = New Control() {}
Else
_controls = GetControls(ctrl.Controls, ctrl, criteria)
End If
End Sub
Public ReadOnly Property Controls As IEnumerable(Of Control)
Get
Return _controls
End Get
End Property
Private Sub FindControls(parent As Control, controls As HashSet(Of Control), criteria As Func(Of Control, Boolean))
If parent Is Nothing Then
Return
End If
For Each ctrl As Control In parent.Controls
If criteria(ctrl) Then
controls.Add(ctrl)
End If
If ctrl.HasChildren Then
FindControls(ctrl, controls, criteria)
End If
Next
End Sub
Private Function GetControls(list As ICollection, parent As Control, criteria As Func(Of Control, Boolean)) As HashSet(Of Control)
If list Is Nothing OrElse parent Is Nothing Then
Return Nothing
End If
Dim controls As HashSet(Of Control) = New HashSet(Of Control)()
For Each ctrl As Control In list
controls.Add(ctrl)
FindControls(parent, controls, criteria)
Next
Return controls
End Function
End Class
الإستخدام
' In form load use the below code
Dim finder As New ControlFinder(Me)
Dim count = finder.Controls.Count
If count > 0 Then
Me.Text = count
End If
Dim count = finder.Controls.Count
If count > 0 Then
Me.Text = count
End If
' or
For Each c As Control In finder.Controls
' do something
Next
For Each c As Control In finder.Controls
' do something
Next
تعديل بسيط علي الكلاس أعلاه
Public Sub New(ctrl As Control, criteria As Func(Of Control, Boolean))
_controls = If(Not criteria(ctrl), New Control() {}, GetControls(ctrl.Controls, ctrl, criteria))
End Sub
Comments
Post a Comment