0

我从目录中获取图片列表并将文件名存储在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
}

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

4

2 回答 2

5

senderPictureBox被点击的:

private void PictureClick(object sender, EventArgs e) {
    PictureBox oPictureBox = (PictureBox)sender;
    // add border, do whatever else you want.
}
于 2012-12-20T18:49:52.857 回答
2

sender参数确实是您的PictureBox,向下转换为对象。以这种方式访问​​它:

var pictureBox = sender as PictureBox;

在它周围绘制边框并不容易,因为您必须重写OnPaintPictureBox 的方法,或者处理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);
    }
}
于 2012-12-20T18:49:27.357 回答