UserControl 主窗口方法调用

UserControl控件调用主窗口方法

1、uc部分需要被主窗口访问的属性和方法需要定义出来
2、方法调用基于委托,这里有输入参数(string)和返回值(int),使用Func<string,int>,uc内部代码直接使用AutoIncr
3、主窗口创建uc时注册具体方法(AutoCount)到委托(Func)

        private void Form3_Load(object sender, EventArgs e) //MainForm
        {
            Color[] c = { Color.AliceBlue,Color.Aqua,Color.Bisque,Color.Aquamarine,Color.Brown };
            for (int i = 1; i < 21; i++)
            {
                UserControl1 uc = new UserControl1(i);
                uc.BorderStyle = BorderStyle.FixedSingle;
                uc.Padding = new Padding(2);
                uc.BackColor = c[i % c.Length];
                uc.AutoIncr += AutoCount;
                flowLayoutPanel1.Controls.Add(uc);
            }
        }

        public int AutoCount(string pid)
        {
            if (count.Keys.Contains(pid))
            {
                count[pid] = count[pid] + 1;
            }
            else
            {
                count.Add(pid, 1);
            }
            return count[pid];
        }
    }
    public partial class UserControl1 : UserControl   //自定义控件
    {
        public int pid { get; set; }
        public SerialPort serialport { get; set; }
        public string sn	{ get { return txt_sn.Text; } }
        public string txt2 	{ get { return textBox2.Text; }}

        public event Func<string, int> AutoIncr;
        public UserControl1(int id)
        {
            InitializeComponent();
            try
            {
                this.pid = id;
                lbl_idx.Text = "P" + id.ToString();
                serialport = new SerialPort("COM" + pid.ToString());
                serialport.Open();
                serialport.DataReceived += Serialport_DataReceived;
                lbl_msg.Text = serialport.PortName + "Ready";
            }
            catch (Exception ex)
            {
                lbl_msg.Text = ex.Message;
                txt_sn.Enabled = false;
                textBox2.Enabled = false;
            }
        }

        private void Serialport_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            SerialPort sp = sender as SerialPort;
            string content = sp.ReadExisting();
            txt_sn.Text = content;
            prosn();
        }
        
        public void prosn()
        {
            string sn = txt_sn.Text;
            if (string.IsNullOrEmpty(sn))
            {
                lbl_msg.Text = "不能为空";
                return;
            }
            int r = AutoIncr("P" + pid.ToString());
            lbl_count.Text = r.ToString();
            txt_sn.Text = "";
        }
    }
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值