自定义控件和事件处理?

时间:2014-08-08 02:44:29

标签: c# winforms custom-controls

我有 Windows自定义控件,其中pictureboxbutton默认为panel。此 Windows自定义控件将添加到 Windows窗体。还有另一个名为form2的窗体。当用户双击自定义控件时,应加载form2。在设计器中,当我双击表单上的自定义控件时,它会为该自定义控件创建一个load()事件。但我需要双击事件,如何做到这一点?

enter image description here

这是发生的事情的图形视图 enter image description here

以下是控件中的代码

    [DefaultEvent("DoubleClick")]
public partial class cntrlImageLoader : UserControl
{
    public cntrlImageLoader()
    {
        InitializeComponent();
    }

    private void btnBrowse_Click(object sender, EventArgs e)
    {
        OpenFileDialog ofd = new OpenFileDialog();
        ofd.InitialDirectory = Environment.SpecialFolder.MyPictures.ToString();
        if (ofd.ShowDialog() == DialogResult.OK)
        {
            pbImage.Image = Image.FromFile(ofd.FileName);
        }
    }

    private void pbImage_Click(object sender, EventArgs e)
    {
        this.cntrlImageLoader_DoubleClick(pbImage, e);
    }

    private void cntrlImageLoader_Load(object sender, EventArgs e)
    {

    }

    private void cntrlImageLoader_DoubleClick(object sender, EventArgs e)
    {

    }
}

这是form1上的调用代码

private void cntrImLdrFront_DoubleClick(object sender, EventArgs e)
{
     //this.cntrImLdrFront.pbImage.DoubleClick += new EventHandler(pbImage_DoubleClick);

}

FrmImageViewer f; // this is form2
private void pbImage_DoubleClick(object sender, EventArgs e)
{
    f= new FrmImageViewer();
    f.MdiParent = this.MdiParent;
    f.Show();
}

1 个答案:

答案 0 :(得分:1)

在类声明中分配属性[DefaultEvent("DoubleClick")]

[DefaultEvent("DoubleClick")]
public partial class MyControl : UserControl
{
}

这将创建在您放置用户控件的设计时双击控件时默认设置的事件。

<强>编辑:

[DefaultEvent("LoadPicture")]
public partial class cntrlImageLoader : UserControl
{
    public delegate void LoadPictureEventHandler(object sender, LoadPictureEventArgs e);
    public event LoadPictureEventHandler LoadPicture;

    private void pbImage_DoubleClick(object sender, EventArgs e)
    {
        if (LoadPicture != null)
        {
            LoadPictureEventArgs ev = new LoadPictureEventArgs();
            LoadPicture(this, ev);
            if (ev.Picture != null)
            {
                pbImage.Image = ev.Picture;
            }
        }
    }          
}

创建另一个类并将该类名提供给LoadPictureEventArgs

public class LoadPictureEventArgs : EventArgs
{
    public Image Picture {get; set;}
    public LoadPictureEventArgs(Image _picture)
    {
        Picture = _picture
    }
    public LoadPictureEventArgs()
                    : base()
    {
    }
}

如何使用它?

//FORM1
private void cntrImLdrFron_LoadPicture(object sender, LoadPictureEventArgs e)
{
    Image img = null;
    //LOAD YOUR IMAGE HERE
    e.Picture = img;

}