using System; using System.Drawing; using System.Linq; using System.Windows.Forms; namespace Widow { public partial class DrawOverlayForm : Form { public event EventHandler WindowDrawn; #region Public Enums, Properties and Fields public bool IsMouseDown { get; set; } public Point StartLocation { get; set; } public Point StopLocation { get; set; } public SolidBrush DrawBrush { get; } public SolidBrush FormBrush { get; } #endregion #region Private Delegates, Events, Enums, Properties, Indexers and Fields private Point CurrentLocation { get; set; } private volatile Bitmap _bitmap; #endregion #region Constructors, Destructors and Finalizers public DrawOverlayForm() { InitializeComponent(); DrawBrush = new SolidBrush(Color.LightBlue); FormBrush = new SolidBrush(Color.White); } #endregion #region Event Handlers private void DrawOverlayForm_MouseDown(object sender, MouseEventArgs e) { IsMouseDown = true; StartLocation = e.Location; } private void DrawOverlayForm_MouseUp(object sender, MouseEventArgs e) { IsMouseDown = false; StopLocation = e.Location; var left = Math.Min(StartLocation.X, StopLocation.X); var top = Math.Min(StartLocation.Y, StopLocation.Y); var width = Math.Abs(StopLocation.X - StartLocation.X); var height = Math.Abs(StopLocation.Y - StartLocation.Y); WindowDrawn?.Invoke(this, new WindowDrawnEventArgs(left, top, width, height)); Close(); } private void DrawOverlayForm_MouseMove(object sender, MouseEventArgs e) { CurrentLocation = e.Location; if (!IsMouseDown) { return; } var selection = new Rectangle( Math.Min(StartLocation.X, CurrentLocation.X), Math.Min(StartLocation.Y, CurrentLocation.Y), Math.Abs(StartLocation.X - CurrentLocation.X), Math.Abs(StartLocation.Y - CurrentLocation.Y)); _bitmap = new Bitmap(Width, Height); using (var canvas = Graphics.FromImage(_bitmap)) { canvas.Clear(Color.White); canvas.FillRectangle(DrawBrush, selection); } Invalidate(); Update(); } private void DrawOverlayForm_Paint(object sender, PaintEventArgs e) { if (_bitmap == null) { return; } var graphics = e.Graphics; graphics.DrawImage(_bitmap, Location.X, Location.Y, Width, Height); _bitmap?.Dispose(); _bitmap = null; } #endregion } }