Question Detecting X button click of a window in winforms.

priyamtheone

Well-known member
Joined
Sep 20, 2007
Messages
94
Programming Experience
Beginner
How can I detect the click event of the close (X) button at the top right corner of the control box of a form/window? Please note, I don't want to know about CloseReason, FormClosing, FormClosed or stuffs like these, unless they are inevitable. I exactly want to detect if the user clicked the X button of the form. Thanks.
 

ProtekNickz

Well-known member
Joined
Oct 22, 2009
Messages
117
Location
UK
Programming Experience
1-3
Code:
    Private Sub frmClose_FormClosing(sender As Object, e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
        If CBool(CloseReason.UserClosing) 'Then checks to see if user has tried to close form
            e.Cancel = True 'and cancels that action here
            MsgBox("User Has tried to close From") ' Really you could put your own event here
        End If
    End Sub
hope this helps, i know you said not in formclosing but off the top of my head is all i can think of right now :)
 

priyamtheone

Well-known member
Joined
Sep 20, 2007
Messages
94
Programming Experience
Beginner
If my form is closed by other means such as its 'Close' menu or by the MDI parent then the CloseReason obtained while FormClosing or FormClosed events are the same as UserClosing. So there's no way to differentiate exactly what action triggered the form-close. Actually, I need to fire a specific action only if the X button is clicked. Hope I could make it clear.
 

JohnH

VB.NET Forum Moderator
Staff member
Joined
Dec 17, 2005
Messages
15,412
Location
Norway
Programming Experience
10+
It is not possible unless you make it a borderless form and implement your own window handling, which means a your own X button and all that, that you can handle the Click event for. In Windows OS the windows title bar including the buttons are handled by the OS, it is only the client area that is managed by the client itself, and all the options you mentioned all has the same meaning of UserClosing, ie it was user that requested the window closed.
 

JuggaloBrotha

VB.NET Forum Moderator
Staff member
Joined
Jun 3, 2004
Messages
4,524
Location
Lansing, MI; USA
Programming Experience
10+
It's messy but you could use a global variable (boolean) to know when the form is closed from somewhere else in your program (just set it to true right before you call the form's close method) and be sure to set it to false in the form's load event

Actually a little cleaner idea of the same concept, make it a property of the form, then set that property to true right before closing the form, or make your own close method that would set it to true then call it's own close method.
 
Top Bottom