[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

Getting click or mouse event from any control on a form

Posted on 2009-12-31
10
Medium Priority
?
314 Views
Last Modified: 2012-05-08
In my winform app. I have a form which have some controls.
I have some code that I need to operate for all the controls when they are clicked.
How can I get the mouse or click event  for ALL controls at once?
0
Comment
Question by:yaron89
  • 3
  • 3
  • 2
  • +1
10 Comments
 
LVL 10

Expert Comment

by:Rakesh Jaimini
ID: 26152854
do you need controls separate event also

one way is use controls collection and iterate this collection and attach event with every control
0
 
LVL 5

Expert Comment

by:bklmnsh
ID: 26152870
assign the same event handler for all controls. just like this
this.button1.Click += new System.EventHandler(this.button1_Click);
this.label1.Click += new System.EventHandler(this.button1_Click);
this.textBox1.Click += new System.EventHandler(this.button1_Click);
0
 
LVL 5

Expert Comment

by:bklmnsh
ID: 26152878
other way to do this is something like this

foreach(Control c in this.Controls)
{
   if (c is Button)
      (c as Button).Click += new EventHandler(this.button1_Click);
   else if (c is TextBox)
      (c as TextBox).Click += new EventHandler(this.button1_Click);
............
and so on
.............
}
0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 10

Expert Comment

by:Rakesh Jaimini
ID: 26153008
hi bklmnsh
you just gave the code for what i said :P
0
 
LVL 86

Expert Comment

by:Mike Tomlinson
ID: 26155868
Another option is to implement the IMessageFilter() Interface for your app and look for WM_LBUTTONDOWN messages.

This approach allows you to get the a notification that the left mouse button has been depressed BEFORE it gets routed to any specific control.

Which approach is best really depends on what you're doing in the app...

See: http://msdn.microsoft.com/en-us/library/system.windows.forms.imessagefilter(VS.80).aspx

    "A class that implements the IMessageFilter interface can be added to the application's message pump to filter out a message or perform other operations before the message is dispatched to a form or control. To add the message filter to an application's message pump, use the AddMessageFilter method in the Application class."

Let me know if you want to see an example.
0
 
LVL 10

Expert Comment

by:Rakesh Jaimini
ID: 26197545
Hi,
Idle mind
can you provide example for the same
0
 
LVL 86

Accepted Solution

by:
Mike Tomlinson earned 2000 total points
ID: 26201781
Sure...here is a SIMPLISTIC example.

Note that since I'm using:

    Control ctl = this.GetChildAtPoint(this.PointToClient(Cursor.Position));

It assumes that all controls are directly contained by the form.  Obviously a more sophisticated approach is necessary for more complex layouts.

The point is to demonstrate that you can get notified for all controls via IMessageFilter...whether this is a better approach is really dependent on what needs to be done when you left click.  ;)

Here's the sample code:
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();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            MyFilter mf = new MyFilter();
            mf.LeftClickPreview += new MyFilter.LeftClick(mf_LeftClickPreview);
            Application.AddMessageFilter(mf);

            this.label1.MouseDown += new MouseEventHandler(label1_MouseDown);
        }

        void label1_MouseDown(object sender, MouseEventArgs e)
        {
            Console.WriteLine("Default Label MouseDown Handler");
        }

        void mf_LeftClickPreview()
        {
            Control ctl = this.GetChildAtPoint(this.PointToClient(Cursor.Position));
            if (ctl != null)
            {
                Console.WriteLine("IMessageFilter Notification: Left Click on " + ctl.Name);
            }
        }
    }

    public class MyFilter : IMessageFilter
    {

        private const int WM_LBUTTONDOWN = 0x201;
        public delegate void LeftClick();
        public event LeftClick LeftClickPreview;

        public bool PreFilterMessage(ref Message m)
        {
            switch (m.Msg)
            {
                case WM_LBUTTONDOWN:
                    LeftClickPreview();
                    break;

                default:
                    break;
            }
            return false;
        }

    }

}

Open in new window

0
 

Expert Comment

by:TelDig
ID: 26315761
Hi Idle Mind,
I came across your example and would like to know what will append if multiple control (by example third party) add MessageFilter to the Application?
Is this will give a situation that depend of who is the first or last to register to the message?

In my situation A third party toolbar "eat up" some keyboard message and process "Shortcut / command key" and return them as handeled via MessageFilter.
This prevent one of my custom control to get the message that should take priority over it.

Can I add a "messageFilter" on my custom control to "preview the message" before the thirdparty toolbar?
Or the only alternative is to relay on the third party and expect they give an event like "beforeProcess shortcut" and from the tool bar, verifying my control is in the state to receive the event and  returning "false" to before process shortcut?

The second alternative required to "tie up" the frame with some custom control specific requirement ;o(

Thanks and hope i can add content to your discussion ;o)
0
 
LVL 86

Expert Comment

by:Mike Tomlinson
ID: 26316742
That's a good question TelDig and I'm pretty sure there is no way to guarantee the order in which subscribers get notified.  It would be up to the third-party control to "play nice" and provide you with its own events.   =\
0
 

Expert Comment

by:TelDig
ID: 26316864
Doh! So in that situation this mean that it will be impossible to have a custom control that "preview keys/shortcut" and be independant of the architecture ;o( Lucky in my case the event is provided and i'm only concerded about the "focused control" and a simple interface on that control will allow me to handle that case.. but need to modify the application frame ;..o(
Thanks
0

Featured Post

Upgrade your Question Security!

Add Premium security features to your question to ensure its privacy or anonymity. Learn more about your ability to control Question Security today.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction This article series is supposed to shed some light on the use of IDisposable and objects that inherit from it. In essence, a more apt title for this article would be: using (IDisposable) {}. I’m just not sure how many people would ge…
Exception Handling is in the core of any application that is able to dignify its name. In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
this video summaries big data hadoop online training demo (http://onlineitguru.com/big-data-hadoop-online-training-placement.html) , and covers basics in big data hadoop .
This video shows how to quickly and easily deploy an email signature for all users in Office 365 and prevent it from being added to replies and forwards. (the resulting signature is applied on the server level in Exchange Online) The email signat…
Suggested Courses
Course of the Month17 days, 23 hours left to enroll

830 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question