RingDotNetfor Ring

Closing a window

A program that has unsaved changes should ask before the window closes. This lesson uses the FormClosing event to ask Save, Don't save or Cancel, cancels the close when the user cancels, and shows what runs after the window has closed.

What you will learn#

Every editor, every form that has data, asks before it closes. This is the pattern.

The program#

samples/UsingDotNet/tutorials/ch10_closing.ring
# closing a window - the FormClosing event: asking to save changes, cancelling the close, and what runs after the form closed
load "dotnet.ring"

using {
	"System.IO"
	"System.Drawing"
	"System.Windows.Forms"
}

# controls and state that the event code uses are global variables
oForm = ""
oEdit = ""
oStatus = ""
cFile = ""
lChanged = False                  # are there changes that are not saved?
cTestAnswer = ""                  # a test sets the answer of the question; empty = ask the user with a message box
nCloseAttempts = 0
lClosed = False

func main

	cFile = new Path().Combine([ new Path().GetTempPath(), "ringdotnet-closing.txt" ])
	oForm = uiForm("Notes",420,260)
	oEdit = uiTextBox(oForm,15,15,380,26)
	oEdit.Text = "my notes"
	uiButton(oForm,"Save",15,55,90,30,"saveNow()")
	uiButton(oForm,"Close",115,55,90,30,"oForm.Close()")
	oStatus = uiLabel(oForm,"No changes",15,100,380,24)

	oEdit.setTextChangedEvent("lChanged = True oStatus.Text = 'There are changes that are not saved'")
	oForm.setFormClosingEvent("onClosing()")             # runs BEFORE the form closes, and can stop it
	oForm.setFormClosedEvent("lClosed = True")           # runs AFTER the form closed: too late to stop it

	uiRun(oForm)
	cleanUp()

func saveNow

	new File().WriteAllText([ :path = cFile, :contents = oEdit.Text ])
	lChanged = False
	oStatus.Text = "Saved"

# The question: Yes = save and close, No = close without saving, Cancel = do not close. A test answers by itself.
func askSave

	if cTestAnswer != ""
		return cTestAnswer
	ok
	return new MessageBox().Show([ :text = "Save the changes?", :caption = "Notes", :buttons = "YesNoCancel", :icon = "Question" ])

# The event arguments (aDotNetArgs[2]) have Cancel: set it to True and the form stays open.
func onClosing

	nCloseAttempts++
	if not lChanged
		return                                            # nothing to save: let the form close
	ok
	cAnswer = askSave()
	if cAnswer = "Yes"
		saveNow()
	but cAnswer = "Cancel"
		aDotNetArgs[2].Cancel = True
	ok

func cleanUp

	if new File().Exists(cFile)
		new File().Delete(cFile)
	ok

How it works#

Remember the changes#

The text box has the event TextChanged; its code sets the global lChanged to true and writes a message in the status label. saveNow writes the file and sets lChanged to false. The program asks about changes only when lChanged is true, so a user who did not change anything is never asked.

FormClosing#

setFormClosingEvent("onClosing()") runs onClosing each time the form is about to close: the user clicked the X, pressed Alt+F4, or the program called Close(). The event arguments are aDotNetArgs[2], and aDotNetArgs[2].Cancel = True stops the close. The function asks the question with a message box with the buttons Yes, No and Cancel; Yes saves and lets the form close, No lets it close without saving, and Cancel sets Cancel. When there are no changes the function returns at once and the form closes.

FormClosed#

setFormClosedEvent runs after the form closed. It is too late to stop the close, but it is the place to release things (a timer, a file, a connection). The test uses it to know that the form really closed: after the answer Cancel lClosed is false, after Yes it is true.

A question that a test can answer#

A message box waits for a person, so the function askSave first looks at cTestAnswer: when a test has set it, that is the answer. The test sets "Cancel" and calls oForm.Close(): the form stays open, was asked once, and nothing was written. Then it sets "Yes" and closes again: the file has the new text, the flag is false and the form closed. The same function asks a real person when cTestAnswer is empty. Writing a question as a function with an answer that can be set from outside is the way to test any program that waits for the user.

The checks of this program are in a separate file, selftest/ch10_closing.ring:

samples/UsingDotNet/tutorials/selftest/ch10_closing.ring
# the checks of ch10_closing.ring: run with  ring ch10_closing.ring --selftest  (the program loads this file and runs selfTest() once its window is shown)

func selfTest

	# no changes yet: closing would not ask anything
	dnAssert("no changes",lChanged,False)

	# a change, and the user answers Cancel: the form stays open
	oEdit.Text = "my notes, changed"
	dnAssert("the change is known",lChanged,True)
	cTestAnswer = "Cancel"
	oForm.Close()
	dnAssert("asked once",nCloseAttempts,1)
	dnAssert("not closed after Cancel",lClosed,False)
	dnAssert("the file was not written",new File().Exists(cFile),False)

	# the user answers Yes: the changes are saved, and the form closes (here the test form is closed by uiTest after this code)
	cTestAnswer = "Yes"
	oForm.Close()
	dnAssert("asked again",nCloseAttempts,2)
	dnAssert("saved on Yes",new File().ReadAllText(cFile),"my notes, changed")
	dnAssert("the form closed",lClosed,True)
	dnAssert("no changes left",lChanged,False)
Note

Close() on a form that was shown with ShowDialog also raises FormClosing; the dialog result is set by the button. A form that was hidden with Hide() is not closed and does not raise the event.

What you learned#

Exercises#

  1. Show the changes flag in the title of the window (Notes *) while there are changes, as editors do.
  2. Add a New button that asks the same question before it clears the text.
  3. Remember the position and the size of the window in the FormClosing event (the tutorial Settings) and restore them at the start.
  4. Ask the question with the text of the changes in it (how many characters were added).

Next#

More than one window

RingDotNet — use .NET classes and methods from Ring programs. Screenshots and output on these pages come from the real samples.