How do I close a form when a user clicks outside the form's window?

前端 未结 8 2087
孤独总比滥情好
孤独总比滥情好 2021-01-12 15:51

I want to close a System.Windows.Forms.Form if the user clicks anywhere outside it. I\'ve tried using IMessageFilter, but even then none of the messages are passed to PreFi

8条回答
  •  死守一世寂寞
    2021-01-12 16:46

    With thanks to p-daddy in this question, I've found this solution which allows me to use ShowDialog:

    protected override void OnShown(EventArgs e)
    {
        base.OnShown(e);
        this.Capture = true;
    }
    
    protected override void OnCaptureChanged(EventArgs e)
    {
        if (!this.Capture)
        {
            if (!this.RectangleToScreen(this.DisplayRectangle).Contains(Cursor.Position))
            {
                this.Close();
            }
            else
            {
                this.Capture = true;
            }
        }
    
        base.OnCaptureChanged(e);
    }
    

提交回复
热议问题