C#分屏控件用法实例
本文实例中的自定义类PictureBox继承于UserControl,最终实现简单的分屏功能。分享给大家供大家参考之用。具体实现代码如下:
publicpartialclassPictureControl:UserControl { publiceventMouseEventHandlerPicControl_DoubleClick; privateintpicNum; ///<summary> ///屏幕个数 ///</summary> publicintPicNum { get{returnpicNum;} set { if(value==4||value==6||value==9||value==12||value==16||value==20||value==25)//只能 是4、6、9、12、16、20、25 { picNum=value; this.SetPictureBox(this.picNum); } else { this.PicNum=12; this.SetPictureBox(this.picNum); } } } publicPictureControl() { this.picNum=4; InitializeComponent(); this.SetPictureBox(this.picNum); } ///<summary> ///根据个数布局PictureBox ///</summary> ///<paramname="num"></param> privatevoidSetPictureBox(intnum) { this.Controls.Clear(); Sizesize=this.Size; switch(num) { case4:this.SetPictureBox(2,2,size);break; case6:this.SetPictureBox(2,3,size);break; case9:this.SetPictureBox(3,3,size);break; case12:this.SetPictureBox(3,4,size);break; case16:this.SetPictureBox(4,4,size);break; case20:this.SetPictureBox(4,5,size);break; case25:this.SetPictureBox(5,5,size);break; } } ///<summary> ///布局pictureBox ///</summary> ///<paramname="x">几行</param> ///<paramname="y">几列</param> ///<paramname="size">当前控件的大小</param> privatevoidSetPictureBox(intx,inty,Sizesize) { intnum=0; for(inti=0;i<x;i++) { for(intj=0;j<y;j++) { PictureBoxpic=newPictureBox(); pic.SizeMode=PictureBoxSizeMode.Zoom;//设置自动缩放 pic.BackColor=Color.White;//设置背景颜色 pic.Location=newPoint((size.Width/y)*j,(size.Height/x)*i);//设置Location pic.BorderStyle=BorderStyle.FixedSingle;//设置边框 pic.MouseDoubleClick+=newMouseEventHandler(pic_MouseDoubleClick);//订阅控件双击事件 pic.Size=newSize(size.Width/y,size.Height/x);//设置控件大小 pic.Tag=num;//设定控件编号即屏幕序号 this.Controls.Add(pic);//添加 num++; } } } voidpic_MouseDoubleClick(objectsender,MouseEventArgse) { if(this.PicControl_DoubleClick!=null) { this.PicControl_DoubleClick(sender,e);//将动态添加的控件的双击事件传向控件体外。 } } privatevoidPictureControl_SizeChanged(objectsender,EventArgse) { this.SetPictureBox(this.picNum); } privatePictureBoxGetPicByIndex(intindex) { foreach(Controlcinthis.Controls) { if(Convert.ToInt32(c.Tag)==index) { return(PictureBox)c; } } PictureBoxp=newPictureBox(); p.Tag=-1; returnp; } ///<summary> ///根据屏幕序号设置图像 ///</summary> ///<paramname="index">屏幕号</param> ///<paramname="img">图像</param> publicvoidSetImageByIndex(intindex,Imageimg) { GetPicByIndex(index).Image=img; } }
希望本文所述实例对大家C#程序设计有所帮助。