PictureBox上的动态点击事件

时间:2012-12-20 18:44:56

标签: c# .net

我从目录中获取图片列表,并将文件名存储在List<String>中。然后我循环遍历其中的每一个并为每个创建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
}

如何获取已点击的并设置其边框颜色?

2 个答案:

答案 0 :(得分:5)

sender是点击的PictureBox

private void PictureClick(object sender, EventArgs e) {
    PictureBox oPictureBox = (PictureBox)sender;
    // add border, do whatever else you want.
}

答案 1 :(得分:2)

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);
    }
}