Rubrik: Controls · ListBox & ComboBox | VB-Versionen: VB2005, VB2008 | 24.03.09 |
CheckBox in der ComboBox Diesmal zeigen wir Ihnen, wie man eine CheckBox im Eingabefeld der ComboBox anzeigen kann. | ||
Autor: Dieter Otter | Bewertung: | Views: 15.601 |
www.tools4vb.de | System: Win2k, WinXP, Win7, Win8, Win10, Win11 | Beispielprojekt auf CD |
Vor kurzem hatten wir Ihnen ein Tipp vorgestellt, mit dem sich ein Bildsymbol im Eingabefeld einer ComboBox anzeigen lässt. Das Grundgerüst dieses Tipps machen wir uns heute zu Nutzen, um anstelle eines Bildsymbols eine CheckBox in der ComboBox anzuzeigen. Die CheckBox verwenden wir dann, um die Auswahl eines Eintrags aus der ComboBox durch den User zu aktivieren bzw. zu sperren. D.h.: ist die CheckBox markiert, darf der Anwender einen Eintrag aus der ComboBox auswählen. Andernfalls soll die Auswahl gesperrt werden.
Erstellen Sie ein neues Projekt und platzieren auf die Form ein ComboBox-Control (ComboBox1), sowie ein CheckBox-Control (CheckBox1). Fügen Sie anschließend nachfolgenden Code ein:
Public Class Form1 ' benötigte API-Deklarationen Private Declare Function SendMessage Lib "user32" _ Alias "SendMessageA" ( _ ByVal hwnd As IntPtr, _ ByVal wMsg As Integer, _ ByVal wParam As Integer, _ ByVal lParam As Integer) As Integer Private Declare Function FindWindowEx Lib "user32" _ Alias "FindWindowExA" ( _ ByVal hwndParent As IntPtr, _ ByVal hwndChildAfter As IntPtr, _ ByVal lpszClass As String, _ ByVal lpszWindow As String) As Integer Private Const EC_LEFTMARGIN = &H1 Private Const EM_SETMARGINS = &HD3
' CheckBox im Eingabefeld einer ComboBox anzeigen Public Sub ComboBox_AddCheckBox(ByVal oForm As Form, _ ByVal oComboBox As ComboBox, _ ByVal oCheckBox As CheckBox) Dim nHWnd As IntPtr Dim nLeft As Integer ' Handle des Eingabefeldes der Combo-TextBox ermitteln With oComboBox nHWnd = FindWindowEx(.Handle.ToInt32, 0, "EDIT", vbNullString) If (nHWnd <> 0) Then ' CheckBox-Eigenschaften festlegen With oCheckBox .Text = "" .BackColor = .BackColor .TabStop = False .AutoSize = False .Size = New Size(13, 13) End With ' CheckBox in das Eingabefeld platzieren oCheckBox.Location = New Point(.Left + 4, .Top + 4) oCheckBox.BringToFront() ' linken Rand des Eingabefeldes der ComboBox neu festlegen nLeft = oCheckBox.Width + 3 Call SendMessage(nHWnd, EM_SETMARGINS, EC_LEFTMARGIN, nLeft) End If End With End Sub
Private Sub Form1_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load ' CheckBox in die ComboBox platzieren ComboBox_AddCheckBox(Me, ComboBox1, CheckBox1) CheckBox1.Checked = True ' ein paar Testeinträge For i As Integer = 1 To 10 ComboBox1.Items.Add("Eintrag " & CStr(i)) Next End Sub
Private Sub CheckBox1_CheckedChanged(ByVal sender As System.Object, _ ByVal e As System.EventArgs) ' ComboBox aktivieren/deaktivieren ComboBox1.Enabled = (CheckBox1.Checked) End Sub
End Class