C#創(chuàng)建自定義控件的示例
在編程過程中,現(xiàn)有的c#控件遠(yuǎn)遠(yuǎn)不能滿足我們的需要,這時(shí)候就需要我們自己來(lái)開發(fā)控件了。本人在開發(fā)自定義控件時(shí)走了一些彎路,寫下此篇,希望能夠給有需要的朋友一些幫助,也借此加深自己的印象。
1.創(chuàng)建自定義控件
2.添加控件,組合成一個(gè)新的控件
自定義控件功能:打開一張圖片,將圖片展示在pictureBox控件中,并將圖片的名稱、大小、尺寸顯示出來(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;已超過最大限制的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(); } } } }
點(diǎn)擊【解決方案】,右鍵彈出窗口,點(diǎn)擊【生成解決方案】
至此,自定義控件的創(chuàng)建已經(jīng)完成!
生成的控件路徑在Debug文件夾下,dll文件
3.自定義控件測(cè)試
新建windows窗體應(yīng)用程序
發(fā)現(xiàn)在左邊的控件工具欄中并沒有剛剛的自定義控件,不要急?。?/p>
選擇工具下的【選擇工具箱項(xiàng)】
瀏覽,選擇dll文件路徑,注意路徑中不能包含中文字符,切記!否則會(huì)出錯(cuò)!
添加成功后,會(huì)發(fā)現(xiàn)工具箱中出現(xiàn)了剛剛定義的控件。
測(cè)試結(jié)果:
以上就是C#創(chuàng)建自定義控件的示例的詳細(xì)內(nèi)容,更多關(guān)于C#創(chuàng)建自定義控件的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
C#使用ScrapySharp實(shí)現(xiàn)多線程下載操作
在現(xiàn)代互聯(lián)網(wǎng)應(yīng)用中,數(shù)據(jù)抓取是一個(gè)常見的需求,無(wú)論是為了數(shù)據(jù)分析、內(nèi)容聚合還是自動(dòng)化測(cè)試,ScrapySharp 是一個(gè)基于 .NET 的輕量級(jí)、高性能的網(wǎng)頁(yè)抓取庫(kù),本文將探討如何在 C# 中使用 ScrapySharp 實(shí)現(xiàn)多線程下載策略,需要的朋友可以參考下2024-08-08