gpt4 book ai didi

c# - 覆盖 ComboBox 的 DrawItem

转载 作者:行者123 更新时间:2023-12-05 08:34:33 26 4
gpt4 key购买 nike

我更改了各种控件的突出显示颜色,并且我计划进行更多更改。因此,我最好创建自己的控件并重用它们,而不是对每个控件进行更改。

我创建了一个新的用户控件,并继承自System.Windows.Forms.ComboBox。问题是我找不到像onClick那样覆盖onDraw的方法。

那么我该如何去覆盖它呢?这是我用于每个控件的代码 onDraw 事件

public void comboMasterUsers_DrawItem(object sender, DrawItemEventArgs e)
{
e.DrawBackground();

Graphics g = e.Graphics;
Brush brush = ((e.State & DrawItemState.Selected) == DrawItemState.Selected) ?
Brushes.LightSeaGreen : new SolidBrush(e.BackColor);

g.FillRectangle(brush, e.Bounds);
e.Graphics.DrawString(comboMasterUsers.Items[e.Index].ToString(), e.Font,
new SolidBrush(e.ForeColor), e.Bounds, StringFormat.GenericDefault);

e.DrawFocusRectangle();
}

谢谢!

最佳答案

给你:

public class myCombo : ComboBox
{
// expose properties as needed
public Color SelectedBackColor{ get; set; }

// constructor
public myCombo()
{
DrawItem += new DrawItemEventHandler(DrawCustomMenuItem);
DrawMode = System.Windows.Forms.DrawMode.OwnerDrawFixed;
SelectedBackColor= Color.LightSeaGreen;
}

protected void DrawCustomMenuItem(object sender, DrawItemEventArgs e)
{
e.DrawBackground();
// a dropdownlist may initially have no item selected, so skip the highlighting:
if (e.Index >= 0)
{
Graphics g = e.Graphics;
Brush brush = ((e.State & DrawItemState.Selected) == DrawItemState.Selected) ?
new SolidBrush(SelectedBackColor) : new SolidBrush(e.BackColor);
Brush tBrush = new SolidBrush(e.ForeColor);

g.FillRectangle(brush, e.Bounds);
e.Graphics.DrawString(this.Items[e.Index].ToString(), e.Font,
tBrush, e.Bounds, StringFormat.GenericDefault);
brush.Dispose();
tBrush.Dispose();
}
e.DrawFocusRectangle();
}
}

您可以考虑在扩展自定义时公开更多属性,这样您就可以在需要时为每个实例更改它们..

另外不要忘记处置您创建的 GDI 对象,例如画笔和钢笔!

编辑:刚刚注意到 BackColor 会隐藏原始属性。将其更改为 SelectedBackColor,它实际上说明了它是什么!

编辑 2: 正如 Simon 在评论中指出的那样,有一个 HasFlag 方法,从 .Net 4.0 开始也可以这样写:

      Brush brush = ((e.State.HasFlag(DrawItemState.Selected) ?

更清晰、更简短。

编辑 3: 实际上,为了在控件上绘图,建议使用 TextRenderer.DrawText 而不是 graphics.DrawString..

关于c# - 覆盖 ComboBox 的 DrawItem,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24475812/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com