Last active
April 12, 2018 23:27
-
-
Save amenayach/0d4cf66de7fae736cdf294da84eb6955 to your computer and use it in GitHub Desktop.
This helps to maintain last used inputs in a winform, let's say you have a Title and Description text boxes in a form F, this class will ensure when the form F is loaded that last entered input in these text boxes will be present at load event
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
namespace System.Windows.Forms | |
{ | |
//This class requires JSON.net package, to install from the nuget console use: | |
//Install-Package Newtonsoft.Json | |
using Newtonsoft.Json.Linq; | |
using System.IO; | |
using System.Linq; | |
public static class StickyInput | |
{ | |
private const string Filename = "appsettings.json"; | |
public static void Stick(this Form form, params Control[] controls) | |
{ | |
if (form != null && (controls?.Any() ?? false)) | |
{ | |
form.Load += (sender, e) => | |
{ | |
var json = GetAppSettings(); | |
var formEntry = (json[form.Name] as JObject) ?? new JObject(); | |
foreach (var control in controls) | |
{ | |
control.Text = formEntry[control.Name]?.ToString(); | |
} | |
}; | |
form.FormClosing += (sender, e) => | |
{ | |
var formEntry = new JObject(); | |
foreach (var control in controls) | |
{ | |
formEntry[control.Name] = control.Text; | |
} | |
SaveAppSettings(form.Name, formEntry); | |
}; | |
} | |
} | |
private static JObject GetAppSettings() | |
{ | |
var jsonFilename = Path.Combine(Directory.GetCurrentDirectory(), Filename); | |
if (!File.Exists(jsonFilename)) | |
{ | |
return new JObject(); | |
} | |
return JObject.Parse(File.ReadAllText(jsonFilename)); | |
} | |
private static void SaveAppSettings(string entry, JObject json) | |
{ | |
var jsonSettings = GetAppSettings(); | |
jsonSettings[entry] = json; | |
var jsonFilename = Path.Combine(Directory.GetCurrentDirectory(), Filename); | |
File.WriteAllText(jsonFilename, jsonSettings.ToString()); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage
In the targeted form constructor: