C#教程

关注公众号 jb51net

关闭
首页 > 软件编程 > C#教程 > C#自定义控件组合控件

C#(Winfrom)自定义控件--组合控件方式

作者:码上写码

文章介绍了创建和使用自定义控件的步骤:首先构建控件库项目,添加TextBox和Button控件并设置透明背景,编写属性及事件处理代码;然后通过测试程序验证功能,最后将控件部署到测试窗体中使用

本例是制作一个简单的自定义控件,然后用一个简单的测试程序,

对于初学者来说,本例子比较简单,只能起到抛石引玉的效果。

我也是在学习当中,今后会将自己所学的逐步写出来和大家交流共享。

创建自定义控件

第一步:创建控件库项目:MyControl

第二步:从工具箱中拖出1个TextBox和Button控件

设置背景为透明

在项目中添加一个Windows窗体程序

第三步:添加处理程序代码

PopControls中定义自定义控件的属性及button事件

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;

namespace MyControls
{
    public partial class PopControls : UserControl
    {
        
        public static string s;
        public PopControls()
        {
            InitializeComponent();
        }
        //定义自定义的属性
        [Browsable(true)]
        [Description("点击按钮,窗体的宽度,单位时像素"),Category("自定义属性"),DefaultValue(0)]
        public int PopWidth { get; set; }
        [Browsable(true)]
        [Description("点击按钮,窗体的高,单位时像素"), Category("自定义属性"), DefaultValue(0)]
        public int PopHeight { get; set; }
        [Browsable(true)]
        [Description("窗体的Text属性"), Category("自定义属性"), DefaultValue(0)]
        public string PopText { get; set; }
        private void btnok_Click(object sender, EventArgs e)
        {
            FrmPop frm = new FrmPop(PopWidth,PopHeight,PopText);
            frm.ShowDialog();

            txtnode.Text = s;
        }
    }
}

FrmPop窗体代码

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace MyControls
{
    public partial class FrmPop : Form
    {
        public FrmPop(int PopWidth,int PopHeight,string PopText)
        {
            InitializeComponent();
            this.ClientSize = new System.Drawing.Size(PopWidth, PopHeight);
            this.Text = PopText;
        }

        private void FrmPop_Load(object sender, EventArgs e)
        {
            for (int i = 0; i < 50; i++)
            {
                //随机数
                string s = Guid.NewGuid().ToString("N");
                listBoxGuid.Items.Add(s);
            }
            
        }

        private void listBoxGuid_DoubleClick(object sender, EventArgs e)
        {
            PopControls.s = listBoxGuid.SelectedItem.ToString();

            this.Close();
        }
    }
}

第四步:测试控件

双击listbox中的数据

第五步:查看成生的控件文件,到该项目文件目录下的bin->debug中可找到。

使用自定义控件

第一步:创建Windows窗体程序

第二步:添加自定义控件

右键选中添加选项卡

在自定义控件下右键点击选择项,弹框如下图:

点击浏览,找到自定义控件项目–bin–debug–Mycontrols.dll文件

选中控件文件 Mycontrols.dll ,单击“打开”按钮,回到自定义工具箱,系统会默认把你刚才选中的控件打上 勾

返回vs编辑器,可看到工具箱中发现PopControls控件:

第三步:拖动1个自定义的控件到测试窗口

第四步:测试自定义控件

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文