当前位置:编程学习 > C#/ASP.NET >>

C# winform 自定义控件点击事件问题

自定义了一个控件如图,代码如下:


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

namespace WindowsFormsApplication1
{
    public partial class UserControl1 : UserControl
    {
        public UserControl1()
        {
            InitializeComponent();
        }
        public void SetNum(int i)
        {
            label4.Text = i.ToString();
        }
    }
}
主form 代码

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

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        int discannum =5;
        private void Form1_Load(object sender, EventArgs e)
        {
            Point pt = new Point();
            UserControl1[] canctrl = new UserControl1[discannum];
            for (int j = 0; j < discannum; j++)
            {
                canctrl[j] = new UserControl1();
                pt.X = j % 3 * 160;
                pt.Y = j / 3 * 150;
                canctrl[j].Location = pt;
                canctrl[j].Click += new EventHandler(canctrl_click);
                this.Controls.Add(canctrl[j]);
                canctrl[j].SetNum(j);

            }
        }
        private void canctrl_click(object sender, EventArgs e)
        {
            int i=0;
            MessageBox.Show("你点了第" + i + "个控件");
        }
    }
}


问题是:1我点击控件中空的地方可以响应事件,但是点击上面的字就不响应事件,如果我想在点击控件中lable,也要响应事件该怎么做?2,我怎么知道是点击的是哪个控件?谢谢大家了。 --------------------编程问答-------------------- 这个label上也加事件 --------------------编程问答-------------------- 如果label上再加事件是不是有点复杂?我这个只4个label,如果有很多呢?点这些label做的事跟点控件空白处做都是一样的啊。 --------------------编程问答-------------------- lable的点击中也调用窗体的点击canctrl_click --------------------编程问答-------------------- 如果自定义控件中有20个label呢,每个label都要加吗? --------------------编程问答--------------------
引用 3 楼 bdmh 的回复:
lable的点击中也调用窗体的点击canctrl_click

我的自定义控件只是个显示用的,想点击任何地方都能调用canctrl_click
补充:.NET技术 ,  C#
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,