Friday, January 4, 2013

How to prevent a form from closing?

How to prevent a form from closing?


This is a very classic question and there are multiples answers. I’ll show you my way to do it not because my way is smarter but only because I want to share my ideas to you.

prevent from closing a form




When you create a form in visual basic 2010 or any other edition including Visual Studio 2010 or 2012, it automatically calls events.

When you simply want to intercept the action, you could simply put a simple MsgBox in the close event.

    Private Sub Form1_FormClosing(sender As Object, e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
        If MsgBox("do you realy want to close this form", MsgBoxStyle.YesNo) = MsgBoxResult.Yes Then
        Else
            e.Cancel = True
        End If

    End Sub



prevent from closing a form

The main problem I have with this method is because there is always more than one way to close a form:

  • Using a NotifyIcon in the TaskBar
  • Using a MenuStripItem
  • Using a shortcut Key combination
  • Using another form or and external command from a other program.
  • Using any thing from your imagination (CTRL+ALT+DEL, laptop battery failure….)


So instead of making a lot of closing code in your program inside private events, I rather make one single close program and use it at large.
I like to make that Close program public because is only a close function. I also think the close function or sub must be easy to access. With a good close function, I could call it from anywhere and make my program more predictable.

In some case, my close function check if there is any remaining thread running or any trouble before closing. This way, I am sure my program is clean.


1 comment: