C# PictureBox上的动态单击事件
我正在从一个目录中获取一个图片列表,并将文件名存储在C# PictureBox上的动态单击事件,c#,.net,C#,.net,我正在从一个目录中获取一个图片列表,并将文件名存储在列表中。然后,我循环浏览其中的每一个,并为它们创建一个PictureBox,然后向它们添加相同的单击事件。控件位于FlowLayoutPanel foreach(String file in this._files){ PictureBox box = new PictureBox(); box.Height = 50; box.Width = 50; box.ImageLocation = file;
列表中。然后,我循环浏览其中的每一个,并为它们创建一个PictureBox
,然后向它们添加相同的单击事件。控件位于FlowLayoutPanel
foreach(String file in this._files){
PictureBox box = new PictureBox();
box.Height = 50;
box.Width = 50;
box.ImageLocation = file;
box.SizeMode = PictureBoxSizeMode.Zoom;
box.Click += this.PictureClick;
this.flowLayoutPanel1.Controls.Add(box);
}
private void PictureClick(object sender, EventArgs e){
// how do I get the one that has been clicked and set its border color
}
如何获取已单击的图片并设置其边框颜色?发送者
参数实际上是您的图片框
,向下转换为对象。通过以下方式访问它:
var pictureBox = sender as PictureBox;
在其周围绘制边框并不容易,因为您必须覆盖PictureBox的OnPaint
方法,或者处理Paint
事件
可以使用此类在图像周围绘制黑色细边框
public class CustomBorderPictureBox : PictureBox
{
public bool BorderDrawn { get; private set; }
public void ToggleBorder()
{
BorderDrawn = !BorderDrawn;
Invalidate();
}
protected override void OnPaint(PaintEventArgs pe)
{
base.OnPaint(pe);
if (BorderDrawn)
using (var pen = new Pen(Color.Black))
pe.Graphics.DrawRectangle(pen, 0, 0, Width - 1, Height - 1);
}
}
sender
是单击的PictureBox
:
private void PictureClick(object sender, EventArgs e) {
PictureBox oPictureBox = (PictureBox)sender;
// add border, do whatever else you want.
}