获取winform任意位置点击事件

版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/wanglei19880622/article/details/8910505

在form类中InitializeComponent(); 后添加代码:

Application.AddMessageFilter(this);


form类中添加方法:类中添加方法:

	bool IMessageFilter.PreFilterMessage(ref Message m)
        {
            if (m.Msg == 0x201)
            {
                Control C = GetControl(this);
                if (C != null)
                    if (C.Parent == null || C.Parent.Name != "panelMenu")//筛选控件C,并设置点击事件要做的事
                    {
                        //c筛选控件C
                        if (C.Parent.Parent == null || C.Parent.Parent.Name != "panelMenu")
                        {
                            this.panelMenu.Visible = false;
                        }
                    }
                return false;
            }
            return false;
        }
        /// <summary>
        /// 循环获取最外层节点控件
        /// </summary>
        /// <param name="C"></param>
        /// <returns></returns>
        Control GetControl(Control C)
        {
            Control Temp = C.GetChildAtPoint(C.PointToClient(Cursor.Position));
            if (Temp == null)
                return C;
            else
                return GetControl(Temp);
        }







展开阅读全文

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

10-22

自定义了一个控件如图,代码如下:rn[img=https://img-bbs.csdn.net/upload/201310/22/1382434790_37138.png][/img]rnrnusing System;rnusing System.Collections.Generic;rnusing System.ComponentModel;rnusing System.Drawing;rnusing System.Data;rnusing System.Linq;rnusing System.Text;rnusing System.Windows.Forms;rnrnnamespace WindowsFormsApplication1rnrn public partial class UserControl1 : UserControlrn rn public UserControl1()rn rn InitializeComponent();rn rn public void SetNum(int i)rn rn label4.Text = i.ToString();rn rn rnrn主form 代码rnrnusing System;rnusing System.Collections.Generic;rnusing System.ComponentModel;rnusing System.Data;rnusing System.Drawing;rnusing System.Linq;rnusing System.Text;rnusing System.Windows.Forms;rnrnnamespace WindowsFormsApplication1rnrn public partial class Form1 : Formrn rn public Form1()rn rn InitializeComponent();rn rnrn int discannum =5;rn private void Form1_Load(object sender, EventArgs e)rn rn Point pt = new Point();rn UserControl1[] canctrl = new UserControl1[discannum];rn for (int j = 0; j < discannum; j++)rn rn canctrl[j] = new UserControl1();rn pt.X = j % 3 * 160;rn pt.Y = j / 3 * 150;rn canctrl[j].Location = pt;rn canctrl[j].Click += new EventHandler(canctrl_click);rn this.Controls.Add(canctrl[j]);rn canctrl[j].SetNum(j);rnrn rn rn private void canctrl_click(object sender, EventArgs e)rn rn int i=0;rn MessageBox.Show("你点了第" + i + "个控件");rn rn rnrnrn[img=https://img-bbs.csdn.net/upload/201310/22/1382434904_677780.png][/img]rn问题是:1我点击控件中空的地方可以响应事件,但是点击上面的字就不响应事件,如果我想在点击控件中lable,也要响应事件该怎么做?2,我怎么知道是点击的是哪个控件?谢谢大家了。 论坛

没有更多推荐了,返回首页