שתף באמצעות


Center the text of a combobox

Question

Sunday, June 10, 2012 5:49 PM

Hello friends, I would like to center the text that appears in a combobox.

What I enter the code or the procedure?

Greetings.

All replies (19)

Sunday, June 10, 2012 6:31 PM ✅Answered | 1 vote

Heres one I helped make up,
http://www.vbforums.com/showthread.php?t=671754

This centers the combo text and the combo list text.

Imports System.ComponentModel
Imports System.Runtime.InteropServices
Public Class ComboBoxEx
    Inherits ComboBox
    Sub New()
        MyBase.DrawMode = Windows.Forms.DrawMode.OwnerDrawFixed
    End Sub
    Protected Overrides Sub OnHandleCreated(ByVal e As System.EventArgs)
        MyBase.OnHandleCreated(e)
        Helpers.CenterComboText(Me)
    End Sub
    Protected Overrides Sub OnTextChanged(ByVal e As System.EventArgs)
        Helpers.CenterComboText(Me)
        MyBase.OnTextChanged(e)
    End Sub
    'We hide this property from the intellisense and property grid to prevent anyone from changing it.
    <Browsable(False), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), EditorBrowsable(EditorBrowsableState.Never)> _
    Public Shadows ReadOnly Property DrawMode() As DrawMode
        Get 'This property is declared merely so we can hide it
            Return MyBase.DrawMode
        End Get
    End Property
    Protected Overrides Sub OnDrawItem(ByVal e As System.Windows.Forms.DrawItemEventArgs)
        Dim txt As String = MyBase.Items(e.Index).ToString
        Dim sf As New StringFormat
        e.DrawBackground()
        sf.Alignment = StringAlignment.Center
        e.Graphics.DrawString(txt, e.Font, New SolidBrush(e.ForeColor), e.Bounds, sf)
        e.DrawFocusRectangle()
    End Sub
End Class
Friend Class Win32API
    <StructLayout(LayoutKind.Sequential)> _
    Public Structure RECT
        Public Left As Integer
        Public Top As Integer
        Public Right As Integer
        Public Bottom As Integer
    End Structure
    Public Const EM_SETMARGINS As Integer = &HD3
    Public Const EC_LEFTMARGIN = &H1
    Public Declare Function FindWindowEx Lib "User32.dll" Alias "FindWindowExA" (ByVal hWnd As IntPtr, ByVal hwndChildAfter As IntPtr, ByVal lpszClass As String, ByVal lpszWindow As String) As IntPtr
    Public Declare Function GetWindowRect Lib "User32.dll" (ByVal hWnd As IntPtr, ByRef lpRect As RECT) As Boolean
    Public Declare Function SendMessage Lib "User32.dll" Alias "SendMessageA" (ByVal hWnd As IntPtr, ByVal Msg As UInteger, ByVal wParam As Integer, ByVal lParam As Integer) As Integer
End Class
Friend Class Helpers
    Public Shared Sub CenterComboText(ByVal cbo As ComboBox)
        ' combo must be set to DropDown style!
        If Not cbo.DropDownStyle = ComboBoxStyle.DropDown Then Return
        ' get handle to Edit box in combo
        Dim cboEdit_hWnd As IntPtr = Win32API.FindWindowEx(cbo.Handle, IntPtr.Zero, "Edit", Nothing)
        ' if handle found set combo edit box text left margin
        If Not cboEdit_hWnd = IntPtr.Zero Then
            ' Determine width of string displayed
            Dim textWidth As Integer = TextRenderer.MeasureText(cbo.Text, cbo.Font).Width
            ' get combo's Edit window size
            Dim rct As Win32API.RECT
            Win32API.GetWindowRect(cboEdit_hWnd, rct)
            ' figure left margin so text appears centered in combo's edit box area.
            Dim leftMargin As Integer = ((rct.Right - rct.Left) - textWidth) \ 2
            ' set left margin of combo's Edit box
            Win32API.SendMessage(cboEdit_hWnd, Win32API.EM_SETMARGINS, Win32API.EC_LEFTMARGIN, leftMargin)
        End If
    End Sub
End Class

Tuesday, June 12, 2012 12:07 AM ✅Answered | 1 vote

Friend,

If you simply paste your code in a form, to test it in vb 2008, it does not work.

Do I need to do something?

I thank your good motivation and help.

Greetings

I have tried it. It is compilable. Do these steps:

  1. Start VB
  2. Create a new Windows Forms application
  3. Add a new Class.
  4. Delete the two lines of the Class.
  5. Paste Edgemeal's code
  6. If you have Option Strict On, you must change
        Public Const EC_LEFTMARGIN = &H1
    to
        Public Const EC_LEFTMARGIN As Integer = &H1
  7. It is compilable now.

Can you compile it, too?

Armin


Tuesday, June 12, 2012 10:54 PM ✅Answered | 1 vote

Hello friend,

I in all steps. But the text of the combobox, still not centered.

It does not work.

Any other suggestion, friend?

Greetings

The steps should demonstrate that it is compilable. If you write "does not work" we do not know what does not work.

You see "Class ComboBoxEx" in Edgemeals code? You can use it instead of the standard Combobox. The steps are:

  1. Compile the project.
  2. Open the Form designer.
  3. Open the toolbox. There is a new item named "ComboBoxEx". You can use it like other controls.

Do you already have Comboboxes on the Form, and do you want to replace them with the new ComboboxEx? If yes, do the following: (it is always good to make a copy of your project before)

  1. In the IDE, close all code and Form designer windows.

  2. Open the solution explorer window.

  3. At the top of the window click on "show all files"

  4. In the solution explorer window, look at the Form that you want to change. There is a "+" in front. Click on it. You now see a file ending with .Designer.vb

  5. Open the .Designer.vb file

  6. Within the file, look for the declaration of the Combobox that you want to replace. It is similar to this:

       Friend WithEvents Combobox1 As System.Windows.Forms.ComboBox

  7. Change System.Windows.Forms.ComboBox to ComboboxEx

  8. Open the "error list" window. There is a compile error now. Double-click on the error. You are taken to the error line. It ends with "New System.Windows.Forms.Combobox"

  9. In this line, replace System.Windows.Forms.Combobox by ComboboxEx

  10. You can repeat steps 6 to 9 for every combobox that you want to replace.

Armin


Sunday, June 17, 2012 7:59 PM ✅Answered | 1 vote

Hi Vitor,

How are you friend?

The best way to fix your combobox problem is:

1- Start new Windows Form Application.

2- Add TextBox (leave the name TextBox1), ComboBox (leave the name ComboBox1) and a Button (leave the name Button1).

3- Size the TextBox1 to match the ComboBox1 in size.

4- Place the ComboBox1 on the top of the TextBox1.

5- You should be able to see the ComboBox1 only!

6- Now paste this code to your application:

Public Class Form1    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load        ComboBox1.Items.Add("Steve")        ComboBox1.Items.Add("John")        ComboBox1.Items.Add("Edward")        ComboBox1.Items.Add("Stanley")        ComboBox1.Items.Add("Murray")        ComboBox1.Items.Add("Basil")        TextBox1.SendToBack()        TextBox1.TextAlign = HorizontalAlignment.Center    End Sub    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click        TextBox1.Text = ComboBox1.SelectedItem        ComboBox1.SendToBack()    End Sub    Private Sub TextBox1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles TextBox1.Click        TextBox1.SendToBack()    End Sub    Private Sub ComboBox1_MouseLeave(ByVal sender As Object, ByVal e As System.EventArgs) Handles ComboBox1.MouseLeave        TextBox1.Text = ComboBox1.SelectedItem        ComboBox1.SendToBack()    End SubEnd Class

7- Now use this idea in your code.

8- You can use the print button event to switch the combobox and textbox.

9- If you have problem let me know.

10- I like it simple and easy :)

GoodLuck Friend


Sunday, June 10, 2012 6:44 PM | 1 vote

Hello Vitor Patricio,

Hello friends, I would like to center the text that appears in a combobox.

What I enter the code or the procedure?

Greetings.

in addition , follow this thread http://social.msdn.microsoft.com/forums/en-US/vbgeneral/thread/e5d22714-7d11-468b-b119-953be31bcc0c/

Regards.


Sunday, June 10, 2012 7:21 PM | 1 vote

This may get you started, but bear in mind that it pads the text to "align" it.

Option Strict On
Public Class Form1
    Private Function CB_Center_String(StrToFit As String, CBox As ComboBox) As String
        Dim g As Graphics = CBox.CreateGraphics
        Dim charWidth As Integer = CInt(g.MeasureString("A", CBox.Font, 10000, StringFormat.GenericTypographic).Width)
        g.Dispose()

        Dim CBoxWidth As Integer = CBox.ClientSize.Width - CBox.Margin.Horizontal
        Dim numberOfChars As Integer = CBoxWidth \ charWidth
        Return StrToFit.PadLeft(StrToFit.Length + ((numberOfChars - StrToFit.Length) \ 2))
    End Function
    Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        Dim ComboBox1 As New ComboBox
        With ComboBox1
            .Width = 250
            .Height = 20
            .Top = 10
            .Left = 10
            '.Font = New Font("Courier New", 8)
        End With
        Me.Controls.Add(ComboBox1)
        Dim string1 As String = "12345678901234567890"
        Dim string2 As String = "ABNDJhkyewKLKJBRET"
        Dim string3 As String = "Good time to invest in Ruthenium"
        ComboBox1.Items.Add(CB_Center_String(string1, ComboBox1))
        ComboBox1.Items.Add(CB_Center_String(string2, ComboBox1))
        ComboBox1.Items.Add(CB_Center_String(string3, ComboBox1))
    End Sub
End Class

Sunday, June 10, 2012 10:49 PM

All the code seems interesting, but I can not fit in my project.

Why is that?

Option Strict On
Option Explicit On
Imports System.Drawing.Printing
Public Class Form2
    Private WithEvents pd As New PrintDocument
    Private WithEvents Button1 As New Button With {.Location = New Point(50, 50), .Text = "print", .Parent = Me}

    Private bmp As Bitmap

    Public listOfNames As New List(Of String)
    '
    '
    '
    Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) _
    Handles MyBase.Load
        ComboBox1.DropDownStyle = ComboBoxStyle.DropDownList
        ' Even though the program should have disallowed it to even
        ' get here if the list of names is empty, let's test it anyway:
        If listOfNames.Count = 0 Then
            MessageBox.Show("The list is empty -- returning to Form1", "Nothing To Show!", _
                            MessageBoxButtons.OK, MessageBoxIcon.Stop)
            ' We'll close the program:
            Me.Close()
        Else
            ' Now show the list of names in the combobox:
            For Each personName As String In listOfNames
                ComboBox1.Items.Add(personName)
                ComboBox105.Items.Add(personName)
            Next
        End If
    End Sub
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

        bmp = New Bitmap(Panel1.ClientSize.Width, Panel1.ClientSize.Height)
        Panel1.DrawToBitmap(bmp, Panel1.ClientRectangle)

        pd.Print()

    End Sub
    Private Sub pd_PrintPage(ByVal sender As Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs) Handles pd.PrintPage

        Dim area = e.PageSettings.PrintableArea
        Dim ar1 = area.Width / area.Height
        Dim ar2 = CSng(bmp.Width / bmp.Height)

        If ar1 > ar2 Then
            Dim NewWidth = bmp.Width * area.Height / bmp.Height
            Dim x = (area.Width - NewWidth) / 2
            e.Graphics.DrawImage(bmp, x, area.Top, NewWidth, area.Height)
        Else
            Dim NewHeight = bmp.Height * area.Width / bmp.Width
            Dim y = (area.Height - NewHeight) / 2
            e.Graphics.DrawImage(bmp, area.Left, y, area.Width, NewHeight)
        End If

        e.HasMorePages = False

    End Sub
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Using g = Graphics.FromHwnd(IntPtr.Zero)
            Panel1.Size = New Size(CInt(21 / 2.54 * g.DpiX), CInt(29.7 / 2.54 * g.DpiY))
        End Using
        Dim ps As New PageSettings
        Dim area = ps.PrintableArea

        Using g = Graphics.FromHwnd(IntPtr.Zero)
            Panel1.Size = New Size(CInt(area.Width / 100 * g.DpiX), CInt(area.Height / 100 * g.DpiY))
        End Using
    End Sub

    Private Sub Panel1_Paint(ByVal sender As System.Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles Panel1.Paint

    End Sub

    Private Sub ComboBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ComboBox1.SelectedIndexChanged

    End Sub

    Private Sub Label28_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)

    End Sub

    Private Sub Panel2_Paint(ByVal sender As System.Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles Panel2.Paint

    End Sub

    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        ComboBox68.DropDownStyle = ComboBoxStyle.Simple
    End Sub

    Private Sub ComboBox105_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs)

    End Sub

    Private Sub ComboBox105_SelectedIndexChanged_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ComboBox105.SelectedIndexChanged

    End Sub
End Class


Sunday, June 10, 2012 11:02 PM | 1 vote

Hello friends, I would like to center the text that appears in a combobox.

What I enter the code or the procedure?

Greetings.

Vitor,

If these examples here work for you then great, but I frankly just don't know.

Please call me Frank :)


Monday, June 11, 2012 2:55 AM | 1 vote

I have no idea what you mean by "can not fit in project"

the function I posted is 8 lines including the function declaration and End Function

The solution posted by Edgemeal is perfect (much better than mine), it goes in its own class, again, how can it "not fit" ?


Monday, June 11, 2012 11:01 PM

Friend,

I tested your code, as well as the Edgemeal. The Edgemeal, when I form a neck, does not work. I still have that study. Your code just starting to find interesting. It worked immediately. Just do not work on my project, because in my project, in each combobox, data is entered and changed in the program, the file:

Private namesList As New List (Of String)    

Private namesFileLocation Application.StartupPath & As String = "\ names.txt" namesList.Add (itm)

For Each PersonName As String In namesList

In its example, data combobox is introduced only once. My program is prepared to insert or delete data in the program. How do I fix this, Friend?

greetings


Monday, June 11, 2012 11:13 PM

Friend,

If you simply paste your code in a form, to test it in vb 2008, it does not work.

Do I need to do something?

I thank your good motivation and help.

Greetings


Tuesday, June 12, 2012 10:34 PM

Hello friend,

I in all steps. But the text of the combobox, still not centered.

It does not work.

Any other suggestion, friend?

Greetings


Thursday, June 14, 2012 11:33 PM

Great friend, Armin:

As always, the contribution of you all, is very important.

Many thanks to all!

Now it works! Show. Live to VB and to all promoters.

Hug


Thursday, June 14, 2012 11:37 PM

Friend, after all it is always possible, center the text of the combobox.

The VB is powerful!

greetings


Sunday, June 17, 2012 5:04 PM

Armin Friend,

Everything was working well, but a problem appeared.

In ComboBoxEx, I have prepared everything to print the same.
But I prepared a small change in appearance.
I put a button, so that at the time of printing only show the box with text inside (no one combobox arrow).
Button have the following code:

ComboBoxEx1.DropDownStyle = ComboBoxStyle.Simple

NOW ANOTHER PROBLEM APPEARS:

The text first appeared centered, when you click this button to change the appearance, ready for printing, IT IS NOT TO BE CENTERED!

Is there any way around this, friend?

greetings


Sunday, June 17, 2012 5:15 PM | 1 vote

Armin Friend,

Vitor,

as I did not write the class, it's better the author responds.

Armin


Wednesday, June 20, 2012 10:51 PM

My friend, Sallemander:

All well and you?

Excellent work. It works and is simple. Now I just have to adapt the idea to my project.

Many thanks.

I hope I can count on you.

Big hug, my friend.


Thursday, June 21, 2012 12:07 AM

I am fine.

If you need more help let us know.

Regards,


Tuesday, February 26, 2013 11:36 PM

Selection combo box form1; see in form 2 text label?

Dear friend,

Will can help me?

I would like to select one of the following names in the combobox of form1, this appeared in the text of the label of form2.
Whenever there is a change or correction, the combobox of form1, form2 of the label,were automatically corrected.

What is the code?

my greetings