Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/jquery-ui/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# PictureBox上的动态单击事件_C#_.net - Fatal编程技术网

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.
}