C#實現創建自定義控件?針對這個問題,這篇文章詳細介紹了相對應的分析和解答,希望可以幫助更多想解決這個問題的小伙伴找到更簡單易行的方法。
1.創建自定義控件
2.添加控件,組合成一個新的控件
自定義控件功能:打開一張圖片,將圖片展示在pictureBox控件中,并將圖片的名稱、大小、尺寸顯示出來
控件如下:
pictureBox1:命名為picBox
label1~label6 :左邊三個顯示文字,右邊三個命名為: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;已超過最大限制的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(); } } } }
點擊【解決方案】,右鍵彈出窗口,點擊【生成解決方案】
至此,自定義控件的創建已經完成!
生成的控件路徑在Debug文件夾下,dll文件
3.自定義控件測試
新建windows窗體應用程序
發現在左邊的控件工具欄中并沒有剛剛的自定義控件,不要急??!
選擇工具下的【選擇工具箱項】
瀏覽,選擇dll文件路徑,注意路徑中不能包含中文字符,切記!否則會出錯!
添加成功后,會發現工具箱中出現了剛剛定義的控件。
測試結果:
關于C#實現創建自定義控件問題的解答就分享到這里了,希望以上內容可以對大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關注億速云行業資訊頻道了解更多相關知識。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。