0

我有 n 个图片框。他们应该动态执行以下事件:

private void pictureBoxMouseHover(object sender, EventArgs e) 
{
    if (sender is PictureBox)
    {
        ((PictureBox)sender).BorderStyle = BorderStyle.FixedSingle;
    }
}

private void pictureBoxMouseLeave(object sender, EventArgs e)
{
    if (sender is PictureBox)
    {
        ((PictureBox)sender).BorderStyle = BorderStyle.None;
    }
}

private void MainMaster_Load(object sender, EventArgs e)
{
    foreach (var control in Controls)
    {
        if (sender is PictureBox)
        {
            PictureBox pb=new PictureBox();
            pb.Name = sender.ToString();
            pb.MouseHover += new System.EventHandler(this.pictureBoxMouseHover);
            pb.MouseLeave += new System.EventHandler(this.pictureBoxMouseHover);
        }
    }
}

我找不到这有什么问题;请帮我。

4

2 回答 2

2

dbaseman是对的,您在遍历控件时使用了错误的变量。

但是,如果您想将此行为添加到所有图片框,那么更好的解决方案是创建自定义图片框,并将其简单地放置在您的表单上:

public class MyPictureBox : PictureBox
{
    protected override void OnMouseHover(EventArgs e)
    {
        BorderStyle = BorderStyle.FixedSingle;
        base.OnMouseHover(e);
    }

    protected override void OnMouseLeave(EventArgs e)
    {
        base.OnMouseLeave(e);
        BorderStyle = BorderStyle.None;
    }
}

创建此类,编译应用程序并将这些自定义图片框从工具箱拖到您的表单中。当鼠标悬停在图片框上时,它们都会显示边框。

于 2012-05-14T07:57:39.790 回答
1

我认为错误在这里:

foreach (var control in Controls)
{
    if (sender is PictureBox)

在这种情况下,发送者将是窗口。我想你有意控制

foreach (var control in Controls)
{
    if (control is PictureBox)
于 2012-05-14T07:47:07.650 回答