Alternatives for 'Handles Me.FormClosing' in modules - vb.net

I would like to know of any alternatives to the 'Handles Me.FormClosing' in modules.
I have created code that will display a confirmation message upon clicking the 'X' button. The issue is, I need to put this code into a module to use on multiple forms where i can call it, however, when I attempt to do this the 'Handles Me.FormClosing' will not work.
Here is the code i am using:
Private Sub Close(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
Dim result As DialogResult = MessageBox.Show("Are you sure you want to Exit the application?", "Exit", MessageBoxButtons.YesNo)
If result = DialogResult.Yes Then
FrmLogin.Close()
Else
e.Cancel = True
End If
End Sub

Whenever you create a new form:
Dim newForm as Form = New YourFormClass()
AddHandler newForm.FormClosing, AddressOf YourModule.Close
This will route all closing events you want through that sub. Then just remove the Handles Me.Closing unless there is something you aren't showing us that makes it relevant.

Try This. I made changes to work as you want :
Module YourModule
Public Function AskFormClosing() As Boolean
Dim result As DialogResult = MessageBox.Show("Are you sure you want to Exit the application?", "Exit", MessageBoxButtons.YesNo)
If result = DialogResult.Yes Then
Return True
Else
Return False
End If
End Function
End Module
And then
Private Sub Close(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
If YourModule.AskFormClosing Then
Application.Exit
Else
e.Cancel = True
End If
End Sub

One possibility ist to create a function in your module which shows the MessageBox and exits Application if "Yes" is clicked else returns False.
Module YourModule
Private dontAskAgain As Boolean
Public Function AskFormClosing() As Boolean
If dontAskAgain = False Then
Dim result As DialogResult = MessageBox.Show("Are you sure you want to Exit the application?", "Exit", MessageBoxButtons.YesNo)
If result = DialogResult.Yes Then
dontAskAgain = True
Application.Exit()
End If
End If
Return dontAskAgain
End Function
End Module
And then you only need to set e.Cancel to the inverted result of the function.
Private Sub Close(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
e.Cancel = Not YourModule.AskFormClosing
End Sub
If you prefer to use AddHandler as suggested by other people, you could use the following method that will lead to the same result.
Module YourModule
Public Sub AskFormClosing(sender As Object, e As FormClosingEventArgs)
If dontAskAgain = False Then
Dim result As DialogResult = MessageBox.Show("Are you sure you want to Exit the application?", "Exit", MessageBoxButtons.YesNo)
If result = DialogResult.Yes Then
dontAskAgain = True
Application.Exit()
Else
e.Cancel = True
End If
End If
End Sub
End Module
And then add the Handler like this:
Dim newForm as Form = New YourFormClass()
AddHandler newForm.FormClosing, AddressOf YourModule.AskFormClosing
But for your main-Form you will need to add the Handler in the Loading Event, like this:
Private Sub frmMain_Load(sender As Object, e As EventArgs) Handles MyBase.Load
AddHandler Me.FormClosing, AddressOf YourModule.AskFormClosing
End Sub

Rather than placing this code in a module for reuse, consider create a base Form that has the behaviour you wish to share and then have you other forms inherit from this base Form (rather than from System.Windows.Forms.Form).
See How to: Inherit Windows Forms on the Microsoft website.

Related

How to prevent a form from closing in btnClose_Click

I am trying to prevent the user from closing the form when the DialogResult.No is True in vb.net. I also tried e.cancel=true but it does not work in btnClose_click. I mentioned that is not FormClosingEventArgs. I want put it in btnClose_Click.
Code copied from OP comment;
Private Sub btnClose_Click(sender As Object, e As EventArgs) Handles btnClose.Click
If CustomMessageBox.Show("Are You Sure?", Buttons.YesNo, Icons.Question,
AnimateStyle.ZoomIn) = Windows.Forms.DialogResult.Yes Then
If Windows.Forms.DialogResult.Yes Then
' ---Close The Form
End If
ElseIf Windows.Forms.DialogResult.No Or Windows.Forms.DialogResult.None Then
' ---Not Closing the Form
End If
End Sub
You need to use the FormClosing Event (or Closing befoce NET 2.0). This Event occurs before the close event and can be canceled.
Private Sub Form1_Closing(sender As Object, e As FormClosingEventArgs ) Handles Me.FormClosing
If CustomMessageBox.Show("Are You Sure?", Buttons.YesNo, Icons.Question,
AnimateStyle.ZoomIn) = Windows.Forms.DialogResult.Yes Then
e.Cancel = true ' <<<< close event will not occur, form stays open
End If
End Sub
FormClosing Event

Is there any way to hide a MessageBox?

Is there any way to hide a MessageBox at form load?
I have used Checkedlistbox, and already there is a checkeditems on load of a Form2.
What I want to do is, when I click Form1 it shows Form2 with Checkedlistbox. My problem is, when I click Form1, it show up MessageBox before Form2.
Here is my code on vb.net:
On Form1:
Private Sub cmdSubmitModifyQuant_Click(sender As Object, e As EventArgs) Handles cmdSubmitModifyQuant.Click
Form2.Show()
End Sub
On Form2:
Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
chklstBox1Fill()
End Sub
Private Sub CheckedListBox1_ItemCheck(sender As Object, e As ItemCheckEventArgs) Handles CheckedListBox1.ItemCheck
If e.NewValue = CheckState.Checked Then
question = MsgBox("Area you sure you want to remove?", MsgBoxStyle.Question + MsgBoxStyle.YesNo, "Message")
If question = MsgBoxResult.Yes Then
'Nevermind
ElseIf question = MsgBoxResult.No Then
e.NewValue = CheckState.Checked
End If
End If
End Sub
In my code you can see that i also need to check checklistbox1.
This issue is probably that inside the chklstBox1Fill method you are checking items in your check box list, this causes the event to raise that shows the checkbox. One way to avoid this would be to set a flag to indicate you are populating the list and not show the message box when the flag is set:
Private FillingList As Boolean
Private Sub chklstBox1Fill()
FillingList = True
'Rest of method here.
FillingList = False
End Sub
Private Sub CheckedListBox1_ItemCheck(sender As Object, e As ItemCheckEventArgs) Handles CheckedListBox1.ItemCheck
If FillingList = True Then
Return
End If
If e.NewValue = CheckState.Checked Then
question = MsgBox("Area you sure you want to remove?", MsgBoxStyle.Question + MsgBoxStyle.YesNo, "Message")
If question = MsgBoxResult.Yes Then
'Nevermind
ElseIf question = MsgBoxResult.No Then
e.NewValue = CheckState.Checked
End If
End If
End Sub
(Forgive my VB.Net, been several years since I wrote any!)
Add a boolean variable that indicates wether your load procedure is complete or not. Doing so will not execute the CheckedChanged until the variable is set to True.
Dim FormLoaded As Boolean = False
Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
chklstBox1Fill()
FormLoaded = True
End Sub
Private Sub CheckedListBox1_ItemCheck(sender As Object, e As ItemCheckEventArgs) Handles CheckedListBox1.ItemCheck
If FormLoaded = False Then Return 'Don't execute the rest of the code if it evaluates to False.
If e.NewValue = CheckState.Checked Then
question = MsgBox("Area you sure you want to remove?", MsgBoxStyle.Question + MsgBoxStyle.YesNo, "Message")
If question = MsgBoxResult.Yes Then
'Nevermind
ElseIf question = MsgBoxResult.No Then
e.NewValue = CheckState.Checked
End If
End If
End Sub

How to close first form?

I have 2 forms in my project. Users cannot exit from the first from, frmOptometry. I have this implemented this way:
Private Sub frmOptometry_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
MessageBox.Show("You can only close the application from the receipt screen!")
e.Cancel = True
End Sub
The second form, frmReceipt can be exited from. I have it implemented this way:
Private Sub frmReceipt_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
If MessageBox.Show("Are you sure you want to quit?",
"Obi-Wan Optometry Closing",
MessageBoxButtons.YesNo,
MessageBoxIcon.Exclamation) =
DialogResult.No Then
e.Cancel = True
Else
frmOptometry.Close()
End If
End Sub
Right now, it does not close the program completely because it goes to the frmOptometry_FormClosing and prevents it. What should I do to fix this? Is there anyway to figure out where the user is trying to shut down the program and then decide from there?
One way to solve this is by introducing a flag (say, called FromReceipt) which indicates who asks the frmOptometry to close itself.
Something like this on frmOptometry will do:
Public FromReceipt As Boolean = False 'Add this
Private Sub frmOptometry_FormClosing(sender As Object, e As FormClosingEventArgs) Handles MyBase.FormClosing
If Not FromReceipt Then 'add this condition
MessageBox.Show("You can only close the application from the receipt screen!")
e.Cancel = True
End If
End Sub
And then on the frmReceipt:
Private Sub frmReceipt_FormClosing(sender As Object, e As FormClosingEventArgs) Handles MyBase.FormClosing
If MessageBox.Show("Are you sure you want to quit?",
"Obi-Wan Optometry Closing",
MessageBoxButtons.YesNo,
MessageBoxIcon.Exclamation) =
DialogResult.No Then
e.Cancel = True
Else
frmOptometry.FromReceipt = True 'Add this line to tell the frmOptometry: this time you can really close it
frmOptometry.Close()
End If
End Sub

Skip Me.FormClosing

i've set a warning message before closing the form, but is there a way to skip it sometimes?
My code:
Sub Me_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
If MessageBox.Show("Are you sure you want to cancel the installation?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = DialogResult.Yes Then
e.Cancel = False
Else
e.Cancel = True
End If
End Sub
but i have a final code that must close the app without this message:
Private Sub Done_Click(sender As Object, e As EventArgs) Handles Done.Click
'need to close without warning
Close()
End Sub
can you help me change this or add something that allows that button to close the form without launching Me.FormClosing?
Use a Boolean flag to determine the installation status (success or fail/abort)
Private installSuccess As Boolean ' False by default.
Private Sub Install()
Try
' Installer logic here
' ...
Me.installSuccess = True
Catch ' ex As Exception
End Try
End Sub
Then:
Private Sub Form1_FormClosing(sender As Object, e As FormClosingEventArgs) _
Handles MyBase.FormClosing
If Me.installSuccess Then
Exit Sub
End If
If MessageBox.Show("Are you sure you want to cancel the installation?", "Warning",
MessageBoxButtons.YesNo,
MessageBoxIcon.Question) = DialogResult.Yes Then
e.Cancel = False
Else
e.Cancel = True
End If
End Sub

Stop form from closing conditionally

My problem is that I don't know a suitable command to stop my code from running. If I use a return statement, like below, the code in the subroutine btnClose will keep running causing the program to close on an error. The form must not close if an error on saving occurs.
Private Sub Save_Customer()
If txtName.text = "" then
msgbox("Error")
return
End If
End sub
Private Sub btnClose_Click(sender As System.Object, e As System.EventArgs) Handles btnClose.Click
save_Customer()
Me.Close()
End Sub
Change the Sub to a Function, then evaluate the return:
Private Function Save_Customer() As Boolean
If txtName.text = "" then
msgbox("Error")
return False
Else
Return True
End If
End sub
Private Sub btnClose_Click(sender As System.Object,
e As System.EventArgs) Handles btnClose.Click
' evaluate the return:
If save_Customer() Then
Me.Close()
End IF
End Sub
You should better intercept Closing event, and Cancel closing via e.Cancel = True. Doing it otherwise would result in too much plumbing. (You can close the form not only via btnClose, right)? Also ALT+F4, Mouse click on X button etc. Be careful though, not to leave your user in a deadlock, where they cannot close your form, and have to fall back to using task manager.
That is probably not the best way around your problem, but you could solve it like this:
Private Function Save_Customer()
If txtName.Text = "" Then
MsgBox("Error")
Return False
Else
Return True
End If
End sub
Private Sub btnClose_Click(sender As System.Object, e As System.EventArgs) Handles btnClose.Click
If Save_Customer() = False Then
Exit Sub
Else
Me.Close()
End if
End Sub
End Class