如何在WinForms的组合框中使选定项居中对齐?

use*_*327 7 .net c# combobox alignment winforms

我有一个带有ComboBox的表单。我找到了该帖子:http : //blog.michaelgillson.org/2010/05/18/left-right-center-where-do-you-align/帮助我将DropDown列表中的所有项目居中对齐。问题是所选项目(comboBox.Text属性中显示的项目)保持左对齐。

如何将所选项目居中对齐?
代码是:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace ComboBoxTextProperty
{
    public partial class Form3 : Form
    {
        public Form3()
        {
            InitializeComponent();

            List<string> source = new List<string>() { "15", "63", "238", "1284", "13561" };
            comboBox1.DataSource = source;
            comboBox1.DrawMode = DrawMode.OwnerDrawFixed;
            comboBox1.DropDownStyle = ComboBoxStyle.DropDown;
            comboBox1.SelectedIndex = 0;
            comboBox1.DrawItem += new DrawItemEventHandler(ComboBox_DrawItem);
    }

    /// <summary>
    /// Allow the text in the ComboBox to be center aligned.
    /// Change the DrawMode Property from Normal to either OwnerDrawFixed or OwnerDrawVariable.
    /// If DrawMode is not changed, the DrawItem event will NOT fire and the DrawItem event handler will not execute.
    /// For a DropDownStyle of DropDown, the selected item remains left aligned but the expanded dropped down list is centered.
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void ComboBox_DrawItem(object sender, DrawItemEventArgs e)
    {
        ComboBox comboBox1 = sender as ComboBox; // By using sender, one method could handle multiple ComboBoxes.
        if (comboBox1 != null)
        {
            e.DrawBackground(); // Always draw the background.               
            if (e.Index >= 0) // If there are items to be drawn.
            {
                StringFormat format = new StringFormat(); // Set the string alignment.  Choices are Center, Near and Far.
                format.LineAlignment = StringAlignment.Center;
                format.Alignment = StringAlignment.Center;

                // Set the Brush to ComboBox ForeColor to maintain any ComboBox color settings.
                // Assumes Brush is solid.
                Brush brush = new SolidBrush(comboBox1.ForeColor);
                if ((e.State & DrawItemState.Selected) == DrawItemState.Selected) // If drawing highlighted selection, change brush.
                {
                    brush = SystemBrushes.HighlightText;
                }
                e.Graphics.DrawString(comboBox1.Items[e.Index].ToString(), comboBox1.Font, brush, e.Bounds, format); // Draw the string.
            }
        }
    }
}
}
Run Code Online (Sandbox Code Playgroud)

Rez*_*aei 7

要使文本水平居中,您需要做两件事:

  1. 要居中对齐下拉菜单项,请使ComboBox所有者绘制并自己居中对齐。
  2. 要使控件的文本区域居中对齐,请找到的Edit控件,ComboBoxES_CENTER为其设置样式以使其居中对齐。

在此处输入图片说明

您可能对此帖子也感兴趣:ComboBox文本“垂直居中对齐”

为了使下拉文本居中对齐,您需要自己处理项目的绘制。为此,请将的DrawMode属性设置ComboBoxOwnerDrawFixed。然后,您可以处理DrawItem事件或覆盖OnDrawItem

要将文本区域的对齐方式设置为居中,您需要找到Edit拥有的控件ComboBox。为此,您可以使用GetComboBoxInfo返回的方法COMBOBOXINFO。下一步是调用GetWindowLong方法以获取编辑控件的样式,然后添加ES_CENTER然后调用SetWindowLong以设置新样式。

using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;
public class MyComboBox : ComboBox
{
    public MyComboBox()
    {
        DrawMode = DrawMode.OwnerDrawFixed;
    }

    [DllImport("user32.dll")]
    static extern int GetWindowLong(IntPtr hWnd, int nIndex);
    [DllImport("user32.dll")]
    static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong);
    const int GWL_STYLE = -16;
    const int ES_LEFT = 0x0000;
    const int ES_CENTER = 0x0001;
    const int ES_RIGHT = 0x0002;
    [StructLayout(LayoutKind.Sequential)]
    public struct RECT
    {
        public int Left;
        public int Top;
        public int Right;
        public int Bottom;
        public int Width { get { return Right - Left; } }
        public int Height { get { return Bottom - Top; } }
    }
    [DllImport("user32.dll")]
    public static extern bool GetComboBoxInfo(IntPtr hWnd, ref COMBOBOXINFO pcbi);

    [StructLayout(LayoutKind.Sequential)]
    public struct COMBOBOXINFO
    {
        public int cbSize;
        public RECT rcItem;
        public RECT rcButton;
        public int stateButton;
        public IntPtr hwndCombo;
        public IntPtr hwndEdit;
        public IntPtr hwndList;
    }
    protected override void OnHandleCreated(EventArgs e)
    {
        base.OnHandleCreated(e);
        SetupEdit();
    }
    private int buttonWidth = SystemInformation.HorizontalScrollBarArrowWidth;
    private void SetupEdit()
    {
        var info = new COMBOBOXINFO();
        info.cbSize = Marshal.SizeOf(info);
        GetComboBoxInfo(this.Handle, ref info);
        var style = GetWindowLong(info.hwndEdit, GWL_STYLE);
        style |= 1;
        SetWindowLong(info.hwndEdit, GWL_STYLE, style);
    }
    protected override void OnDrawItem(DrawItemEventArgs e)
    {
        base.OnDrawItem(e);
        e.DrawBackground();
        var txt = "";
        if (e.Index >= 0)
            txt = GetItemText(Items[e.Index]);
        TextRenderer.DrawText(e.Graphics, txt, Font, e.Bounds,
            ForeColor, TextFormatFlags.Left | TextFormatFlags.HorizontalCenter);
    }
}
Run Code Online (Sandbox Code Playgroud)

注意:我将整个逻辑放在派生的控件中MyComboBox,以使其更可重用且更易于应用,但是,显然,您可以不继承而仅依靠现有ComboBox控件的事件来做到这一点。您还可以通过添加TextAlignment允许设置文本对齐方式的属性来稍微增强代码。

  • 我将整个逻辑放在名为MyComboBox的派生控件中,以使其更可重用且更易于应用,但是,显然,您可以在不继承的情况下,仅依靠现有`ComboBox`控件的事件就可以做到这一点。 (2认同)