gpt4 book ai didi

c# - 设置WinForm ListBox的背景

转载 作者:行者123 更新时间:2023-11-30 14:44:15 25 4
gpt4 key购买 nike

有人知道在 WinForms C# 中将背景图像插入列表框的方法吗?

最佳答案

好吧,您必须从 ListBox 继承一个新控件。为此,在您的解决方案中创建一个类型为“Windows 控件库”的新项目,并在文件控件的源代码文件中使用以下代码:

public partial class ListBoxWithBg : ListBox
{
Image image;
Brush brush, selectedBrush;

public ListBoxWithBg()
{
InitializeComponent();

this.DrawMode = DrawMode.OwnerDrawVariable;
this.DrawItem += new DrawItemEventHandler(ListBoxWithBg_DrawItem);
this.image = Image.FromFile("C:\\some-image.bmp");
this.brush = new SolidBrush(Color.Black);
this.selectedBrush = new SolidBrush(Color.White);
}

void ListBoxWithBg_DrawItem(object sender, DrawItemEventArgs e)
{
e.DrawBackground();
e.DrawFocusRectangle();
/* HACK WARNING: draw the last item with the entire image at (0,0)
* to fill the whole ListBox. Really, there's many better ways to do this,
* just none quite so brief */
if (e.Index == this.Items.Count - 1)
{
e.Graphics.DrawImage(this.image, new Point(0, 0));
}
else
{
e.Graphics.DrawImage(this.image, e.Bounds, e.Bounds, GraphicsUnit.Pixel);
}
Brush drawBrush =
((e.State & DrawItemState.Selected) == DrawItemState.Selected)
? this.selectedBrush : this.brush;
e.Graphics.DrawString(this.Items[e.Index].ToString(), this.Font, drawBrush, e.Bounds);
}
}

为简洁起见,我省略了所有设计器代码等,但您必须记住在控件的 Dispose 方法中对图像和画笔进行 Dispose .

关于c# - 设置WinForm ListBox的背景,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/724132/

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