C#實(shí)現(xiàn)創(chuàng)建自定義控件?針對(duì)這個(gè)問(wèn)題,這篇文章詳細(xì)介紹了相對(duì)應(yīng)的分析和解答,希望可以幫助更多想解決這個(gè)問(wèn)題的小伙伴找到更簡(jiǎn)單易行的方法。
1.創(chuàng)建自定義控件
2.添加控件,組合成一個(gè)新的控件
自定義控件功能:打開(kāi)一張圖片,將圖片展示在pictureBox控件中,并將圖片的名稱(chēng)、大小、尺寸顯示出來(lái)
控件如下:
pictureBox1:命名為picBox
label1~label6 :左邊三個(gè)顯示文字,右邊三個(gè)命名為:lblName lblLength lblSize
button1:命名為btnOpen
代碼如下:
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.IO; namespace WindowsFormsControlLibrary1 { public partial class UserControl1: UserControl { public UserControl1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { OpenFileDialog ofdPic = new OpenFileDialog(); ofdPic.Filter = "JPG(*.JPG;*.JPEG);gif文件(*.GIF);PNG(*.PNG)|*.jpg;*.jpeg;*.gif;*.png"; ofdPic.FilterIndex = 1; ofdPic.RestoreDirectory = true; ofdPic.FileName = ""; if (ofdPic.ShowDialog() == DialogResult.OK) { string sPicPaht = ofdPic.FileName.ToString(); FileInfo fiPicInfo = new FileInfo(sPicPaht); long lPicLong = fiPicInfo.Length / 1024; string sPicName = fiPicInfo.Name; string sPicDirectory = fiPicInfo.Directory.ToString(); string sPicDirectoryPath = fiPicInfo.DirectoryName; Bitmap bmPic = new Bitmap(sPicPaht); if (lPicLong > 400) { MessageBox.Show("此文件大小為" + lPicLong + "K;已超過(guò)大限制的K范圍!"); } else { Point ptLoction = new Point(bmPic.Size); if (ptLoction.X > picBox.Size.Width || ptLoction.Y > picBox.Size.Height) { picBox.SizeMode = PictureBoxSizeMode.Zoom; } else { picBox.SizeMode = PictureBoxSizeMode.CenterImage; } } picBox.LoadAsync(sPicPaht); lblName.Text = sPicName; lblLength.Text = lPicLong.ToString() + " KB"; lblSize.Text = bmPic.Size.Width.ToString() + "×" + bmPic.Size.Height.ToString(); } } } }