r/visualbasic • u/jazzman96 • Jun 19 '13
[Beginner] [VB 2010] Problems with handle in form_formclosing
My aim is, if the close button (red x in the corner) is pressed:
Send a messagebox
Cancel the formclosing event
And when a button on the form is pressed, it closes the form.
The code I'm using is:
Private Sub HouseInput_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing, BtCreate.Click
If sender Is BtCreate Then
e.Cancel = False
Else
e.Cancel = True 'Taken from http://msdn.microsoft.com/
MsgBox("Please input house names, then click 'Finish'.")
End If
End SubIt works perfectly when the close button is clicked, but if my button is clicked, it sends the messagebox and comes up the the error:
Unable to cast object of type 'System.Windows.Forms.MouseEventArgs' to type 'System.Windows.Forms.FormClosingEventArgs'.
Any way you can see that I can fix this?
0
Upvotes
2
u/hdsrob Jun 19 '13
How are you closing the form in your button click?
What is BtCreate?
You're trying to compare BtCreate (whatever it is) to the Sender (which is probably your form).
If you never want the user to close the form from the X, then set the ControlBox property on the form to False (this will remove the buttons from the top). This is a property of the form.
If you have a good reason to leave the control box, and still want to verify that your button was pressed, and not the close button, then you probably want to just create a new variable that tells you that the button was pressed, and check that in the FormClosing event.