Monday, March 5, 2012

VB.NET - Check to see if "X" Button was Clicked

If you want to be able to check if the red "X" button was clicked on the form, you must add this code to the code of the main form:





Private Const WM_SYSCOMMAND As Int32 = &H112
    Private Const SC_CLOSE As Int32 = &HF060
    '*Do not try to step into this procedure, once you're in, you're usually stuck.
    Protected Overrides Sub WndProc(ByRef m As Message)
        If m.Msg = WM_SYSCOMMAND Then
            Select Case m.WParam.ToInt32()
                Case SC_CLOSE
                    'MsgBox("Form gets closed.")
                    cGenBlnClickedX = True
            End Select

        End If
        MyBase.WndProc(m)
    End Sub



I use this code with my DataGridView validation.  I have row validation with my DataGridView, however if the user clicks the "X" button I do not want my grid to go through validation so I have the following code inside of a function to check to see if validation is needed when entering the RowValidating event handler:


If cGenBlnClickedX = True Then
                Exit Function
            End If





*Note about this code - when stepping through code this will appear to show up at random times.  You cannot step line by line your way out of it.  There are a few tricks to getting around this. 1) the easiest thing to do is instead of stepping line by line, "step out" of the function and you will continue on as usual. 2) when debugging, comment this code out and then put it back in when done debugging. 3) you can go to the line of code you were on before you stepped into this code.  Go to the line of code after it and "run to cursor"

No comments:

Post a Comment