How do I set a click event for a form?

前端 未结 6 771
名媛妹妹
名媛妹妹 2021-01-05 10:37

I have a c# form (let\'s call it MainForm) with a number of custom controls on it. I\'d like to have the MainForm.OnClick() method fire anytime someone clicks on the form re

6条回答
  •  情深已故
    2021-01-05 10:58

    I recommend creating a base form for the other forms in your application to inherit. Add this code to your base form to create a new event called GlobalMouseClickEventHandler:

    namespace Temp
    {
        public delegate void GlobalMouseClickEventHander(object sender, MouseEventArgs e);
    
        public partial class TestForm : Form
        {
            [Category("Action")]
            [Description("Fires when any control on the form is clicked.")]
            public event GlobalMouseClickEventHander GlobalMouseClick;
    
            public TestForm()
            {
                InitializeComponent();
                BindControlMouseClicks(this);
            }
    
            private void BindControlMouseClicks(Control con)
            {
                con.MouseClick += delegate(object sender, MouseEventArgs e)
                {
                    TriggerMouseClicked(sender, e);
                };
                // bind to controls already added
                foreach (Control i in con.Controls)
                {
                    BindControlMouseClicks(i);
                }
                // bind to controls added in the future
                con.ControlAdded += delegate(object sender, ControlEventArgs e)
                {
                    BindControlMouseClicks(e.Control);
                };            
            }
    
            private void TriggerMouseClicked(object sender, MouseEventArgs e)
            {
                if (GlobalMouseClick != null)
                {
                    GlobalMouseClick(sender, e);
                }
            }
        }
    }
    

    This solution will work not only for top-level controls, but also nested controls such as controls placed inside of panels.

提交回复
热议问题