如何在 WinForms 的 ComboBox 中居中对齐所选项目?
Posted
技术标签:
【中文标题】如何在 WinForms 的 ComboBox 中居中对齐所选项目?【英文标题】:How to center-align a selected Item in a ComboBox in WinForms? 【发布时间】:2020-03-13 08:21:00 【问题描述】:我有一个带有 ComboBox 的表单。我找到了帖子: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.
【问题讨论】:
您还需要覆盖 Paint 事件来执行此操作。我建议您从ComboBox
控件创建一个新的派生类,并同时覆盖OnPaint
和OnDrawItem
。
Center the text of a combobox 也应该有帮助。
【参考方案1】:
要使文本水平居中,你需要做两件事:
-
要使下拉菜单项居中对齐,请让
ComboBox
所有者绘制并自己绘制项目,居中对齐。
要使控件的文本区域居中对齐,请找到ComboBox
的Edit
控件并为其设置ES_CENTER
样式以使其也居中对齐。
您可能也对此帖子感兴趣:ComboBox Text Align Vertically Center。
示例
要使下拉文本居中对齐,您需要自己处理项目的绘制。为此,请将ComboBox
的DrawMode
属性设置为OwnerDrawFixed
。然后您可以处理DrawItem
事件或覆盖OnDrawItem
。
要设置文本区域居中对齐,您需要找到ComboBox
拥有的Edit
控件。为此,您可以使用返回COMBOBOXINFO
的GetComboBoxInfo
方法。下一步是调用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
属性来稍微增强代码。
【讨论】:
我将整个逻辑放在一个名为MyComboBox
的派生控件中,以使其更可重用且更易于应用,但是,显然您可以在没有继承的情况下仅依靠现有事件的事件来执行此操作ComboBox
控制。
支持/兼容的函数应该是GetWindowLongPtr
和SetWindowLongPtr
(我也忘记提了,刚想起来)。我发现这个声明在我测试过的所有情况下都有效:[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)] internal static extern IntPtr SetWindowLongPtr(IntPtr hWnd, int nIndex, IntPtr dwNewLong);
。 GetWindowLongPtr
也一样(当然,IntPtr dwNewLong
除外)。在 32 位应用程序中,这些功能会自动回退到以前的版本。以上是关于如何在 WinForms 的 ComboBox 中居中对齐所选项目?的主要内容,如果未能解决你的问题,请参考以下文章
C# - Winforms - Combobox - 避免选择更新数据源的第一项
WinForms ComboBox DropDown 和 Autocomplete 窗口都出现