如果需要查看更多文章,請微信搜索公眾號 csharp編程大全,需要進C#交流群群請加微信z438679770,備注進群, 我邀請你進群! ! !
---------------------------------------------------------------------------------------------------------------------------------------------------------
在編程程序中,現有的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檔案路徑,注意路徑中不能包含中文字符,切記!否則會出錯!
添加成功后,會發現工具箱中出現了剛剛定義的控制元件,

測驗結果:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
如果需要查看更多文章,請微信搜索公眾號 csharp編程大全,需要進C#交流群群請加微信z438679770,備注進群, 我邀請你進群! ! !
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/173440.html
標籤:C#
上一篇:C# 編碼約定
下一篇:C#下拉框集合元素寫法
