Save Layout
Saves the current position and optionally the size of a form to a shared XML layout file.
This function works in conjunction with RestoreLayout.
- Only saves the layout if the form is in normal window state (not minimized or maximized).
- Uses a shared XML layout file located in formLayoutsBasePath.
- The layout data is organized by application name and form name.
- If the corresponding application or form nodes do not exist, they are created.
- The position is always saved; width and height are saved only if saveSize is True.
- If saveSize is False, any existing size elements are removed.
- Thread-safe via SyncLock on a shared synchronization object.
VB
Public Sub SaveLayout(f As Form,
Optional saveSize As Boolean = True)
If f.WindowState <> FormWindowState.Normal Then Exit Sub
SyncLock syncObj
If Not Directory.Exists(formLayoutsBasePath) Then Directory.CreateDirectory(formLayoutsBasePath)
Dim doc = LoadFormLayoutXml()
Dim appName = GetAppNameSafe()
Dim formName = GetEffectiveFormName(f, appName)
Dim appNode = doc.Root.Elements("app").
FirstOrDefault(Function(a) a.Attribute("name")?.Value = appName)
If appNode Is Nothing Then
appNode = New XElement("app", New XAttribute("name", appName))
doc.Root.Add(appNode)
End If
Dim formNode = appNode.Elements("form").
FirstOrDefault(Function(el) el.Attribute("name")?.Value = formName)
If formNode Is Nothing Then
formNode = New XElement("form", New XAttribute("name", formName))
appNode.Add(formNode)
End If
formNode.SetElementValue("x", f.Location.X)
formNode.SetElementValue("y", f.Location.Y)
If saveSize Then
formNode.SetElementValue("width", f.Size.Width)
formNode.SetElementValue("height", f.Size.Height)
Else
formNode.Element("width")?.Remove()
formNode.Element("height")?.Remove()
End If
doc.Save(formLayoutsFilePath)
End SyncLock
End Sub