Click here to Skip to main content
15,886,012 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
Hello,

I have been trying to implement wndproc override in windows form to detect a mouse click outside the form.

I've been reading everywhere on forums and I dont understand why my code doesnt work. Its supposed to be simple.

this is my code:

C#
protected override void WndProc(ref Message m)
        {
            if (m.Msg == WM_LBUTTONDOWN)
            {
                MessageBox.Show("Mouse Clicked!");
            }
            base.WndProc(ref m);
        }


I'm using Visual Studio 2008 and Windows 7 OS.

Thank you for your help.
Posted

As Pete said, the mouse has to be inside the window associated with the window message queue for the WndProc to get the messages. If you need to see external mouse events, you need to capture the mouse or install a Windows hook. There are a lot of options (and pitfalls.) Try this article:

Processing Global Mouse and Keyboard Hooks in C#[^]
 
Share this answer
 
Based on your reply to my other post:

The window that receives the message here is the desktop. Clicking the desktop will not result in your form receiving the message. Remember that I said that the WndProc is per window - your window isn't the one that's receiving the message, so it won't propagate this.
 
Share this answer
 
Which form have you added this code to? Messages are pumped to the window that is interested in them, so you would need to ensure that you have added this function to the form that you were interested in receiving the click in, rather than the form you want to exclude.
 
Share this answer
 
Comments
bilalchb 19-May-10 5:33am    
Hello,

thank you for your reply. I added the code above to the form that is supposed to capture the click. then i minimize the form, and i try clicking on the desktop. im sure i am missing something, but im new to this and i cant figure it out. Thanks.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900