[英]Dynamic click event on PictureBox
我从目录中获取图片列表,并将文件名存储在List<String>
。 然后,我遍历所有这些对象,并为每个对象创建一个PictureBox
,然后向每个对象添加相同的click事件。 控件在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
}
如何获得被点击的边框并设置其边框颜色?
sender
是被单击的PictureBox
:
private void PictureClick(object sender, EventArgs e) {
PictureBox oPictureBox = (PictureBox)sender;
// add border, do whatever else you want.
}
sender
参数确实是您的PictureBox
,向下转换为对象。 通过这种方式访问它:
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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.