Outside mouse events might be dispatched to some other application, so they might not logically exist for a regular .NET application. My first response would be this:
you don't really need it. The behavior you want would contradict the accepted UI model of the OS; it would also drives your customers crazy.
However, just to make the answer complete, I can tell that you can technically do it. You can use one of the two approaches.
First one would provide limited behavior. You did not say what's supposed to be below your form in Z order. It could be another f of the form of the same application. You could have that form filling the entire screen. It can be maximized, but not necessarily. If this is the case, handle the click in this form underneath and write a handle to close a form on top. It also could be the event
System.Windows.Forms.Form.Activated
or the overridden virtual method
OnActivated
of the form underneath. Handle it to close the form on top if it was there during activation of the form underneath.
The second approach is universal, but will only work on Windows because it required some code written in native Windows API. Please see:
http://msdn.microsoft.com/en-us/library/windows/desktop/ms632589%28v=vs.85%29.aspx[
^].
You can use a hook in two ways: using P/Invoke or a mixed-mode C++/CLI + C++ project (managed+unmanaged), where you can always use Windows APU in native code and wrap it in a managed "ref" C++/CLI classes.
There is one reason to prefer C++ with C++/CLI. Here is why: you need to handle an event outside your application with a hook. It means that you need to install a
global hook. According to Microsoft documentation, a global hook can only work if you call the function
SetWindowsHookEx
in a native Windows DLL which you cannot write in C# with P/Invoke anyway. You could write this executable module in pure C++ (native code) and provide some API for .NET via P/Invoke. If you would use unmanaged C++, why not using also C++/CLI to cover interoperability with .NET? Please see:
http://msdn.microsoft.com/en-us/library/windows/desktop/ms644990%28v=vs.85%29.aspx[
^].
If you need learn P/Invoke, please see:
http://en.wikipedia.org/wiki/P/Invoke[
^],
http://msdn.microsoft.com/en-us/library/Aa712982[
^].
This CodeProject article can also be useful:
Essential P/Invoke[
^].
About C++/CLI, please see:
http://en.wikipedia.org/wiki/C%2B%2B/CLI[
^],
http://www.ecma-international.org/publications/standards/Ecma-372.htm[
^],
http://msdn.microsoft.com/en-us/library/xey702bw.aspx[
^].
[EDIT]
You might ask: "Which way would be the best?". My answer is: the first one. Not implementing this ill behavior at all is by far superior to any other decision.
Good luck,
—SA