combobox 如何让text居中_C# ComboBox控件上的文本能不能居中显示?

本文介绍了如何在C#中使ComboBox控件的文本居中显示。通过设置DrawMode为OwnerDrawFixed,并处理DrawItem事件,可以实现各项目居中。具体步骤包括在Visual Studio创建项目,设置ComboBox属性,以及编写DrawItem事件处理函数来计算并绘制居中文本。
摘要由CSDN通过智能技术生成

展开全部

可以居中显示。32313133353236313431303231363533e58685e5aeb931333337613738实现方法为将ComboBox.DrawMode设置为DrawMode.OwnerDrawFixed,

对ComboBox的DrawItem事件编程,各个项目居中显示。

具体步骤如下:

(1)在Visual Studio中创建一个“Windows 窗体应用程序”项目。在Form1上布置一个ComboBox控件

(2)Form1窗体代码Form1.csusing System.Drawing;

using System.Windows.Forms;

namespace WindowsFormsApplication1

{

public partial class Form1 : Form

{

public Form1()

{

InitializeComponent();

// 允许代码重新绘制,固定大小

comboBox1.DrawMode = DrawMode.OwnerDrawFixed;

string[] items = {

"项目",

"项目 1",

"项目 10",

"项目 100",

"项目 1000",

"项目 10000"

};

comboBox1.Items.AddRange(items);

}

// 将comboBox1中的项目居中显示!

private void comboBox1_DrawItem(object sender,

DrawItemEventArgs e)

{

string s = this.comboBox1.Items[e.Index].ToString();

// 计算字符串尺寸(以像素为单位)

SizeF ss = e.Graphics.MeasureString(s, e.Font);

// 水平居中

float left = (float)(e.Bounds.Width - ss.Width) / 2;

if (left 

float top = (float)(e.Bounds.Height - ss.Height) / 2;

// 垂直居中

if (top 

top = top + this.comboBox1.ItemHeight * e.Index;

// 输出

e.DrawBackground();

e.DrawFocusRectangle();

e.Graphics.DrawString(

s,

e.Font,

new SolidBrush(e.ForeColor),

left, top);

}

}

}

(3)运行效果

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值