Just a warning before we get started that the solution isn't going to be pretty, AFAIK you cannot do this completely within managed code.
Now then:
In order to intercept messages to other application you are going to need to make some native calls using User32.dll. If you want to figure all this out the hard way you want to start with SetWindowsHookEx.
Assuming you aren't a masochist there is a nice C# library I found on CodeProject that will make life much easier than manually trying to intercept those messages yourself. Setup a callback for the mouse messages with the X and Y coordinates for the mouse position you can determine if it is within the bounds of your Rectangle
using its Contains
method.
specifiedRegion.Contains(mouseLocation); //where mouseLocation is a Point
User32 also has the functions you will need to get a Device Context for the screen:
[DllImport("User32.dll")]
public static extern IntPtr GetDC(IntPtr hwnd);
[DllImport("User32.dll")]
public static extern void ReleaseDC(IntPtr dc);
To get the DC for the screen use the following call to GetDC
:
IntPtr screenDC = GetDC(IntPtr.Zero);
With this DC we can get our C# Graphics
object and start drawing.
Graphics g = Graphics.FromHdc(screenDC);
Remember to dispose the Graphics
object and release the DC after you finish with it or you will have a memory leak.
g.Dispose();
ReleaseDC(screenDC);