Rubrik: Controls | VB-Versionen: VB2005, VB2008 | 26.02.10 |
Controls einer Form in die richtige TabStop-Folge bringen Alle Controls einer Form oder alle Controls eines Typs oder mehrerer Typen werden mit Hilfe einer Klasse in die richtige Tabstopp-Reihenfolge gebracht. | ||
Autor: Dietrich Herrmann | Bewertung: | Views: 11.839 |
ohne Homepage | System: Win2k, WinXP, Win7, Win8, Win10, Win11 | Beispielprojekt auf CD |
Durch Zufall fand ich auf diesem Link eine Lösung zu genanntem Problem.
Ich zitiere mal den ursprünglichen Autoren: "Man merkt es, wenn man schnell mal eine Windows Form mit vielen Controls 'belegt' und dabei nicht auf die Reihenfolge geachtet hat. In diesem Beispiel gibt's eine TabStopSorter-Klasse, der man einfach eine Form im Konstruktor übergeben muss, und schon sind die TabStopps sortiert."
Und genau das Problem hatte ich öfters schon- vor allem, wenn man die Controls in Anzahl und/oder Location im Zuge der Entwicklung immer mal verändern muss. Wenn man die folgende Klasse zur Verfügung hat, kann man eben schnell die richtige Tabstop-Reihenfolge herstellen.
Ich habe den ursprünglichen Code noch etwas ergänzt. Man kann nun noch in einem Array angeben, welche Typen von Controls in die Sortierung einbezogen werden sollen.
Die Klasse:
Public Class TabStopSorter
Public Sub New(ByVal StartControl As Control, _ Optional ByVal typCtrl() As Control = Nothing) Dim TmpListe As New List(Of Control) Dim i As Integer = 0 For Each C As Control In StartControl.Controls If typCtrl Is Nothing Then TmpListe.Add(C) Else For j As Short = 0 To typCtrl.Length - 1 Dim ty As Type = C.GetType If ty.Equals(typCtrl(j).GetType) Then TmpListe.Add(C) End If Next End If Next TmpListe.Sort(New ControlComparer) For Each C As Control In TmpListe C.TabIndex = I I += 1 If C.Controls.Count > 0 Then Dim x As New TabStopSorter(C) End If Next End Sub
Private Class ControlComparer Implements IComparer(Of Control) Public Function Compare(ByVal x As Control, ByVal y As Control) As Integer _ Implements System.Collections.Generic.IComparer(Of Control).Compare If x.Top <> y.Top Then Return x.Top.CompareTo(y.Top) Else Return x.Left.CompareTo(y.Left) End If End Function End Class
End Class
Zwei Beispiele der Verwendung
1. So werden alle Controls auf einer Form Tabstop-mäßig sortiert:
Dim ctrlSorter As New TabStopSorter(Me)
2. und so nur die Textboxen und Checkboxen
Dim cy() As Control = {New TextBox, New CheckBox} Dim ctrlSorter As New TabStopSorter(Me, cy)