Capture or Detect mouse click on or outside Windows Form using C#.NET

Sometimes in case of Windows form application where we have multiple windows opened and we need to find on which window user has clicked. One method to find this is to capture the mouse click message. Here is the sample code to close form if mouse click happen outside the form. 

 public partial class frmTest : Form
    {
        class WindowCaptureChanged : NativeWindow
        {
            public CaptureChanged OnCaptureChanged;

            protected override void WndProc(ref Message m)
            {
                if (m.Msg == 533)     // WM_CAPTURECHANGED
                    OnCaptureChanged();
                base.WndProc (ref m);
            }
        }
        public delegate void CaptureChanged();
        public CaptureChanged OnCaptureChanged;
        WindowCaptureChanged wcc ;

        public frmTest()
        {           
            InitializeComponent();
            wcc = new WindowCaptureChanged();
            wcc.AssignHandle (Handle);
            wcc.OnCaptureChanged +=
                      new CaptureChanged (CaptureChangedEventHandler);            
        }

        private void CaptureChangedEventHandler()
        {
            // event call on mouse clicked message captured
            if (!this.Capture)
            {
                if (!this.RectangleToScreen(this.DisplayRectangle).                        Contains(Cursor.Position))
                {
                    this.Close ();
                }
                else
                {
                    this.Capture = true;
                }
            }
        }


Comments