StringCollection
1つの解決策は、ユーザー設定を使用することです(編集:コメントでは、アプリケーションを閉じるときにこれは保持されないと言っています。これはユーザー設定を使用することの全体的なポイントであるため、そうではありません...)。
すべての行で、コントロールの位置と名前を文字列として保存する必要があります。
120;140;MyName
ユーザーが新しいボタンを追加するときは、次のStringCollection
ようにアイテムを作成します。
private void make_BookButtonAndStore(int x, int y, string name)
{
make_Book(x,y,name);
Properties.Settings.Default.ButtonStringCollection.Add(String.Format("{0};{1};{2}", book1.Location.X, book1.Location.Y, book1.Name));
Properties.Settings.Default.Save();
}
private void make_Book(int x, int y, string name)
{
// this code is initializing the book(button)
Button book1 = new Button();
Image img = button1.Image;
book1.Image = img;
book1.Name = name;
book1.Height = img.Height;
book1.Width = img.Width;
book1.Location = new Point(44 + x, 19 + y);
book1.Click += new EventHandler(myClickHandler);
groupBox1.Controls.Add(book1);
}
StringCollection
次に、各行を読み取り、場所と名前を抽出してmake_book
再度呼び出すことにより、すべての項目からボタンを作成するコードが必要になります(ボタンが 2 倍になるため、新しいメソッドではありません)。make_BookButtonAndStore
StringCollection
最初のボタンを追加する前に、new
キーワードを使用して を作成する必要がある場合があることに注意してください。
EDIT
そのような設定を作成する方法を説明するには: プロジェクトのプロパティに移動し、[設定] タブに移動します。という名前の新しい設定を作成し、ButtonStringCollection
タイプSystem.Collections.Specialized.StringCollection
とスコープを選択しますUser
。
フォームのコンストラクターで、次の行を追加します。
if (Properties.Settings.Default.ButtonStringCollection == null)
Properties.Settings.Default.ButtonStringCollection = new StringCollection();
次に、上で提供したコードを追加してボタンを作成します。また、フォームのLoad
イベント ハンドラーで、次のようなものを追加します。
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, parts[2]);
}
}
}