温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

C#实现创建自定义控件

发布时间:2020-10-28 16:41:04 来源:亿速云 阅读:164 作者:Leah 栏目:开发技术

C#实现创建自定义控件?针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。

1.创建自定义控件

C#实现创建自定义控件

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

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

控件如下:

pictureBox1:命名为picBox

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

button1:命名为btnOpen

C#实现创建自定义控件

代码如下:

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

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

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

C#实现创建自定义控件

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

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

C#实现创建自定义控件

测试结果:

C#实现创建自定义控件

关于C#实现创建自定义控件问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注亿速云行业资讯频道了解更多相关知识。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI