You may need to use Global Mouse hook for this.
This[
^] should help. I am not too much aware of this so won't be much of help here.
Although for drawing on the desktop, you can use this:
[DllImport("User32.dll")]
static extern IntPtr GetDC(IntPtr hwnd);
[DllImport("User32.dll")]
static extern void ReleaseDC(IntPtr dc);
In the method:
IntPtr yourDesktop = GetDC(IntPtr.Zero);
using (Graphics graphics = Graphics.FromHdc(yourDesktop)) {
graphics.DrawRectangle(Brushes.Black, mouseDownX, mouseDownY, Cursor.Position.X, Cursor.Position.Y);
}
ReleaseDC(yourDesktop);
These are the pieces that can help you. Now this is how the code should work:
1. Track the global mouse down and set those coordinates to (mouseDownX, mouseDownY). Also start a System.Timers.Timer in the same method. Try to keep the
interval
as low as possible*.
2. In the Elapsed event, use the graphics related code I have placed above.
3. Track the global mouse up and set that as final (X,Y). This point should replace the Cursor.Position coordinates.
Once the drawing thing is done, stop the timer so that it doesn't draw things anymore.
*Any other window movement will cause the repaint of desktop so to provide a smoother drawing, you should draw regularly.