c# - 如何在 WinForms 的 ComboBox 中居中对齐所选项目?

标签 c# .net winforms combobox alignment

我有一个带有组合框的表单。我找到了帖子:http://blog.michaelgillson.org/2010/05/18/left-right-center-where-do-you-align/这帮助我将下拉列表中的所有项目居中对齐。问题是所选项目(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.
            }
        }
    }
}
}

最佳答案

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

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

enter image description here

您可能也对这篇文章感兴趣:ComboBox Text Align Vertically Center

示例

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

要将文本区域的对齐方式设置为居中,您需要找到 EditComboBox 拥有的控件。为此,您可以使用 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);
    }
}

注意:我将整个逻辑放在名为 MyComboBox 的派生控件中,以使其更可重用且更易于应用,但是,显然您可以在不继承的情况下完成此操作,只需依赖于现有的 ComboBox 控件。您还可以通过添加允许设置文本对齐方式的 TextAlignment 属性来增强代码。

关于c# - 如何在 WinForms 的 ComboBox 中居中对齐所选项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58906520/

相关文章:

c# - System.Web.Mvc.HtmlHelper' 不包含 CheckBox 的定义

.net - 从 .NET 应用程序拖动到 Windows 资源管理器时强制放置为快捷方式对象

c# - 无论我的表单是否具有焦点,我都可以确保我的控件捕获第一个事件吗?

c# - 使用 DataTable 将数据加载到 DataGridView 的进度条

c# - WebAPI 路由 : Combining Attributes and HttpConfiguration settings

c# - 在数据库中存储图像 - 网络桌面应用程序

asp.net - MonoTouch 和 .NET 上的 TimeZoneInfo 不匹配

c# - 根据内容的宽度调整标签宽度

C# 合并 2 个字典并在它们之间添加值

c# - 为什么在 C# 中使用 global 关键字?