File Handling: Form Closing Event

Tutorial is a continuation of our previous topic called “File Handling: Adding a Save As Command”. But this time we’re going to focus on how to use the form closing event in visual basic. Basically FormClosing event occurs when the user click the close button and the form is being closed. When the form is closed, it releases all the associated resources with the form. To start with this application lets open first our last project called “FileHandling”. Then at the code view window, go to a class name and choose the (Form1 events) then FormClosing for Method name. And this looks like as shown below: And inside the Form1_FormClosing sub procedure, add the following code:
  1. Dim Result As DialogResult
  2. 'if the current unsaved changes occur we will have to use this option
  3. If RichTextBox1.Text <> "" Then
  4.         If savedoc = True Then
  5.                 Result = MessageBox.Show("Would you like to save changes?", "Confirm Exit", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
  6.                 If Result = Windows.Forms.DialogResult.Yes Then
  7.                         SaveFileDialog1.ShowDialog()
  8.                         Dim myStreamWriter As System.IO.StreamWriter
  9.                         SaveFileDialog1.Filter = "Text [*.txt*]|*.txt|All Files [*.*]|*.*"
  10.                         SaveFileDialog1.CheckPathExists = True
  11.                         SaveFileDialog1.Title = "Save File"
  12.                         SaveFileDialog1.ShowDialog(Me)
  13.                         Try
  14.                                 myStreamWriter = System.IO.File.AppendText(SaveFileDialog1.FileName)
  15.                                 myStreamWriter.Write(RichTextBox1.Text)
  16.                                 myStreamWriter.Flush()
  17.                         Catch ex As Exception
  18.                                 MessageBox.Show("There has been an error in the saving process")
  19.                         End Try
  20.                         savedoc = True
  21.                         Application.Exit()
  22.                 End If
  23.                 If Result = Windows.Forms.DialogResult.No Then
  24.                         Application.Exit()
  25.                 End If
  26.         Else : Application.Exit()
  27.         End If
  28. Else : Application.Exit()
  29. End If
The code above will perform when the user click the close or the button with an X in the upper-right corner of the form causes to display a dialog box confirming the user to save the changes the current file. And it looks like as shown below: When the user select “Yes” option, the program will process the saving same what we did on our last topic about “File Handling: Writing and Saving a Text File”. Else when the user click “No” it will terminate the application automatically. And here’s all the code for this application:
  1. Public Class Form1
  2.     'set the savedoc variable value as true
  3.     Dim savedoc As Boolean = True
  4.  
  5.     Private Sub menuOpen_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles menuOpen.Click
  6.  
  7.         'declare open as new openFiledialog so that when the Open Sub menu is click,
  8.         'the OpenfileDialog will appear.
  9.         Dim Open As New OpenFileDialog()
  10.         'it is declare as System input and output Streamreader
  11.         'it reads characters from byte stream in a particular encoding
  12.         Dim myStreamReader As System.IO.StreamReader
  13.         'in an open dialog box, it will give an opening filter for the current filenames,
  14.         'or the save file types.  
  15.         Open.Filter = "Text [*.txt*]|*.txt|All Files [*.*]|*.*"
  16.         'it checks if the file is exist or not
  17.         Open.CheckFileExists = True
  18.         'sets the openfile dialog name as "OpenFile"
  19.         Open.Title = "OpenFile"
  20.         Open.ShowDialog(Me)
  21.  
  22.         Try
  23.             'it opens the selected file by the user
  24.             Open.OpenFile()
  25.             'opens the existing file
  26.             myStreamReader = System.IO.File.OpenText(Open.FileName)
  27.             'it reads the streams from current position to the end of position and display the result to RichTextBox as Text
  28.             RichTextBox1.Text = myStreamReader.ReadToEnd()
  29.         Catch ex As Exception
  30.             'it will catch if any errors occurs
  31.             MsgBox(ex.Message, MsgBoxStyle.Information)
  32.         End Try
  33.     End Sub
  34.  
  35.     Private Sub menuSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles menuSave.Click
  36.         'call the savefiledialog
  37.         SaveFileDialog1.ShowDialog()
  38.         'we use StreamWriter for writing characters to a stream
  39.         Dim myStreamWriter As System.IO.StreamWriter
  40.         'we set default for savefiledialog filter
  41.         SaveFileDialog1.Filter = "Text [*.txt*]|*.txt|All Files [*.*]|*.*"
  42.         'set the checkpath to true
  43.         SaveFileDialog1.CheckPathExists = True
  44.         'set the Savefiledialog title
  45.         SaveFileDialog1.Title = "Save File"
  46.  
  47.         Try
  48.             'gets a string containing the filename selected in the dialog box
  49.             myStreamWriter = System.IO.File.AppendText(SaveFileDialog1.FileName)
  50.             'it writes the string to stream
  51.             myStreamWriter.Write(RichTextBox1.Text)
  52.             'clears all buffers for the current writer and causes any
  53.             'buffered data to be written to the underlying stream
  54.             myStreamWriter.Flush()
  55.         Catch ex As Exception
  56.             'catch unnecesary errors
  57.             MsgBox(ex.Message)
  58.  
  59.         End Try
  60.         'shows we have saved the most recent changes
  61.         savedoc = True
  62.  
  63.  
  64.     End Sub
  65.  
  66.     Private Sub menuSaveAs_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles menuSaveAs.Click
  67.         'show the savefiledialog
  68.         SaveFileDialog1.ShowDialog()
  69.         'if the user encode the file and click save
  70.         If SaveFileDialog1.ShowDialog = DialogResult.OK Then
  71.             'it create a streamwriter to write in to the file
  72.             Dim writer As New System.IO.StreamWriter(SaveFileDialog1.FileName, False)
  73.             'get the content of Richtextbox and write to a stream
  74.             writer.Write(RichTextBox1.Text)
  75.             'close the writer
  76.             writer.Close()
  77.             'it gets the data contains by the control and save the filename for later use.
  78.             RichTextBox1.Tag = SaveFileDialog1.FileName
  79.  
  80.         End If
  81.     End Sub
  82.  
  83.     Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
  84.  
  85.         Dim Result As DialogResult
  86.         'if the current unsaved changes occur we will have to use this option
  87.         If RichTextBox1.Text <> "" Then
  88.             If savedoc = True Then
  89.                 Result = MessageBox.Show("Would you like to save changes?", "Confirm Exit", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
  90.                 If Result = Windows.Forms.DialogResult.Yes Then
  91.                     SaveFileDialog1.ShowDialog()
  92.                     Dim myStreamWriter As System.IO.StreamWriter
  93.                     SaveFileDialog1.Filter = "Text [*.txt*]|*.txt|All Files [*.*]|*.*"
  94.                     SaveFileDialog1.CheckPathExists = True
  95.                     SaveFileDialog1.Title = "Save File"
  96.                     SaveFileDialog1.ShowDialog(Me)
  97.                     Try
  98.                         myStreamWriter = System.IO.File.AppendText(SaveFileDialog1.FileName)
  99.                         myStreamWriter.Write(RichTextBox1.Text)
  100.                         myStreamWriter.Flush()
  101.                     Catch ex As Exception
  102.                         MessageBox.Show("There has been an error in the saving process")
  103.                     End Try
  104.                     savedoc = True
  105.                     Application.Exit()
  106.                 End If
  107.                 If Result = Windows.Forms.DialogResult.No Then
  108.                     Application.Exit()
  109.                 End If
  110.             Else : Application.Exit()
  111.             End If
  112.         Else : Application.Exit()
  113.         End If
  114.  
  115.     End Sub
  116. End Class

Add new comment