1using System; 2using System.Drawing; 3using System.Windows.Forms; 4 5namespace WindowCapture.UI 6{ 7 public class KeyCaptureDialog : Form 8 { 9 private static readonly Color DarkBg = Color.FromArgb(30, 30, 32); 10 private static readonly Color DarkPanel = Color.FromArgb(40, 40, 42); 11 private static readonly Color TextColor = Color.FromArgb(200, 200, 200); 12 private static readonly Color DimText = Color.FromArgb(120, 120, 120); 13 14 public Keys CapturedKey { get; private set; } 15 16 public KeyCaptureDialog(string actionName) 17 { 18 Text = "Press a key"; 19 Size = new Size(300, 120); 20 FormBorderStyle = FormBorderStyle.None; 21 MaximizeBox = false; 22 MinimizeBox = false; 23 StartPosition = FormStartPosition.CenterParent; 24 KeyPreview = true; 25 BackColor = DarkBg; 26 27 Paint += (s, e) => 28 { 29 using (var pen = new Pen(DarkPanel, 2)) 30 e.Graphics.DrawRectangle(pen, 0, 0, Width - 1, Height - 1); 31 }; 32 33 Label lbl = new Label(); 34 lbl.Text = "Press key for: " + actionName; 35 lbl.Location = new Point(0, 30); 36 lbl.Size = new Size(Width, 24); 37 lbl.TextAlign = ContentAlignment.MiddleCenter; 38 lbl.ForeColor = TextColor; 39 lbl.Font = new Font("Segoe UI", 10f); 40 Controls.Add(lbl); 41 42 Label lblHint = new Label(); 43 lblHint.Text = "ESC to cancel"; 44 lblHint.Location = new Point(0, 65); 45 lblHint.Size = new Size(Width, 20); 46 lblHint.TextAlign = ContentAlignment.MiddleCenter; 47 lblHint.ForeColor = DimText; 48 lblHint.Font = new Font("Segoe UI", 9f); 49 Controls.Add(lblHint); 50 51 KeyDown += delegate(object s, KeyEventArgs e) 52 { 53 if (e.KeyCode == Keys.Escape) 54 { 55 DialogResult = DialogResult.Cancel; 56 Close(); 57 } 58 else 59 { 60 // Ignore standalone modifier presses (Ctrl/Shift/Alt/Win) — capturing them as a 61 // binding produces a key that can never match a real keystroke. Wait for an actual key. 62 if (e.KeyCode == Keys.ControlKey || e.KeyCode == Keys.ShiftKey || 63 e.KeyCode == Keys.Menu || e.KeyCode == Keys.LWin || e.KeyCode == Keys.RWin) 64 return; 65 CapturedKey = e.KeyCode; 66 DialogResult = DialogResult.OK; 67 Close(); 68 } 69 }; 70 } 71 } 72}