java 制作自定义控件_C#创建自定义控件的示例

在编程过程中,现有的c#控件远远不能满足我们的需要,这时候就需要我们自己来开发控件了。本人在开发自定义控件时走了一些弯路,写下此篇,希望能够给有需要的朋友一些帮助,也借此加深自己的印象。

1.创建自定义控件

10b9dea5d1adc31602ed418eb85a8345.png

2.添加控件,组合成一个新的控件

自定义控件功能:打开一张图片,将图片展示在pictureBox控件中,并将图片的名称、大小、尺寸显示出来

控件如下:

pictureBox1:命名为picBox

label1~label6 :左边三个显示文字,右边三个命名为:lblName lblLength lblSize

button1:命名为btnOpen

99b4090d652b1ee5d4063344e7bf8f0c.png

代码如下:

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窗体应用程序

发现在左边的控件工具栏中并没有刚刚的自定义控件,不要急!!

选择工具下的【选择工具箱项】

f2bc8802189647df9dd9d1c3f03a2526.png

浏览,选择dll文件路径,注意路径中不能包含中文字符,切记!否则会出错!

添加成功后,会发现工具箱中出现了刚刚定义的控件。

6a899efa45e7633881ffa2b327e52f5e.png

测试结果:

ca6660c3443c923cdca2c05436e0c4e0.png

以上就是C#创建自定义控件的示例的详细内容,更多关于C#创建自定义控件的资料请关注脚本之家其它相关文章!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值