我想保存用户在程序执行过程中创建的文本和单个按钮功能。为此,我使用 Properties.Settings.Default 和我创建的 ButtonStringCollection 集合。
我尝试使用另一个表格来填写,但我来到了InputBox。关闭程序后,它会“忘记”创建的按钮的所有文本,并且需要重新输入它们,并且没有什么可以阻止更改值。我希望保留这些值,但我不知道可以使用什么机制。 所有代码
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.Serialization.Formatters.Soap;
using System.IO;
using System.Collections.Specialized;
using Microsoft.VisualBasic;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
int x1 = 10;
public string name;
public Form1()
{
InitializeComponent();
if (Properties.Settings.Default.ButtonStringCollection == null)
Properties.Settings.Default.ButtonStringCollection = new StringCollection();
}
private void make_Book(int x, int y)
{
name = Interaction.InputBox("Enter Name", "", "", 300,300);
Form2 form2 = new Form2();
Button book1 = new Button();
// book1.Name = name;
book1.Text = name;
book1.Height = 50;
book1.Width = 70;
book1.Location = new Point(44 + x, 19 + y);
//book1.Click += new EventHandler(myClickHandler);
flowLayoutPanel1.Controls.Add(book1);
}
private void make_BookButtonAndStore(int x, int y)
{
make_Book(x, y);
Properties.Settings.Default.ButtonStringCollection.Add(String.Format("{0};{1};{2}", x, y, name));
Properties.Settings.Default.Save();
}
private void Form1_Load(object sender, EventArgs e)
{
foreach (string line in Properties.Settings.Default.ButtonStringCollection)
{
if (!String.IsNullOrWhiteSpace(line))
{
// The line will be in format x;y;name
string[] parts = line.Split(';');
if (parts.Length >= 3)
{
int x = Convert.ToInt32(parts[0]);
int y = Convert.ToInt32(parts[1]);
make_Book(x, y);
}
}
}
}
private void button1_Click(object sender, EventArgs e)
{
// Form2 form2 = new Form2();
// form2.Show();
// form2.ShowDialog();
make_BookButtonAndStore(x1 += 80, 20);
}
private void button2_Click(object sender, EventArgs e)
{
if (flowLayoutPanel1.Controls.Count > 0)
{
flowLayoutPanel1.Controls.RemoveAt(0);
Properties.Settings.Default.ButtonStringCollection.RemoveAt(0);
Properties.Settings.Default.Save();
}
else
MessageBox.Show("На панеле больше нет кнопок");
}
}
}
创建一个文件来存储所有按钮数据。序列化值得学习,对于未来的项目也是如此。
下载 NuGet 包 Newtonsoft.Json,并创建一个类来处理该问题:
using Newtonsoft.Json;
[JsonObject(MemberSerialization.OptIn)]
public class myButton : Button
{
//...
//..
// Create your own button...
//..
}
public static class Buttons
{
private static string defaultPath = @$"{Directory.GetCurrentDirectory()}\buttons\myButtonList.obj";
private static JsonSerializerSettings serializerSettings = new JsonSerializerSettings()
{
NullValueHandling = NullValueHandling.Include,
Formatting = Formatting.Indented,
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
};
public static List<myButton> ButtonList { get; private set; } = new List<myButton>();
public static List<myButton> TryLoading(string? Path = null)
{
Path ??= defaultPath;
if(File.Exists(@Path))
{
try
{
string FileContent = File.ReadAllText(Path);
ButtonList = JsonConvert.DeserializeObject<List<myButton>>(FileContent, serializerSettings) ?? [];
}
catch (Exception ex)
{
throw new Exception("Loading failed", ex);
}
}
return ButtonList;
}
public static bool Save(string? Path = null)
{
Path ??= defaultPath;
try
{
if (!Directory.Exists(Path))
{
Directory.CreateDirectory(Path.Substring(0, Path.LastIndexOf("\\")-1));
}
string Jsonstring = JsonConvert.SerializeObject(ButtonList, serializerSettings);
File.WriteAllText(Path, Jsonstring);
return true;
}
catch (Exception ex)
{
throw new Exception("Save failed", ex);
}
}
}
表格1:
private void Form1_Load(object sender, EventArgs e)
{
if (Tools.Buttons.TryLoading().Count > 0)
{
Tools.Buttons.ButtonList.ForEach(x =>
{
myFlowPanel.Controls.Add(x);
});
}
}
所有按钮数据都将被很好地格式化(即):
[
{
"Name": "aaaa",
"Text": "btn_aaaa",
"Location": "54, 29",
"Size": "70, 50"
}
]