Don Kirkby によって受け入れられた回答と彼が作成した WindowSettings クラスに基づいて、標準フォームから CustomForm を派生させて、すべてのフォームに記述される同一のコードの量を減らすことができます。たとえば、次のようになります。
using System;
using System.Configuration;
using System.Reflection;
using System.Windows.Forms;
namespace CustomForm
{
public class MyCustomForm : Form
{
private ApplicationSettingsBase _appSettings = null;
private string _settingName = "";
public Form() : base() { }
public Form(ApplicationSettingsBase settings, string settingName)
: base()
{
_appSettings = settings;
_settingName = settingName;
this.Load += new EventHandler(Form_Load);
this.FormClosing += new FormClosingEventHandler(Form_FormClosing);
}
private void Form_Load(object sender, EventArgs e)
{
if (_appSettings == null) return;
PropertyInfo settingProperty = _appSettings.GetType().GetProperty(_settingName);
if (settingProperty == null) return;
WindowSettings previousSettings = settingProperty.GetValue(_appSettings, null) as WindowSettings;
if (previousSettings == null) return;
previousSettings.Restore(this);
}
private void Form_FormClosing(object sender, FormClosingEventArgs e)
{
if (_appSettings == null) return;
PropertyInfo settingProperty = _appSettings.GetType().GetProperty(_settingName);
if (settingProperty == null) return;
WindowSettings previousSettings = settingProperty.GetValue(_appSettings, null) as WindowSettings;
if (previousSettings == null)
previousSettings = new WindowSettings();
previousSettings.Record(this);
settingProperty.SetValue(_appSettings, previousSettings, null);
_appSettings.Save();
}
}
}
これを使用するには、コンストラクターでアプリケーション設定クラスと設定名を渡します。
CustomForm.MyCustomForm f = new CustomForm.MyCustomForm(Properties.Settings.Default, "formSettings");
これは、リフレクションを使用して、設定クラスとの間で以前の設定を取得/設定します。Save 呼び出しを Form_Closing ルーチンに入れるのは最適ではない場合があります。これを削除して、メイン アプリが終了するたびに設定ファイルを保存することができます。
通常の形式として使用するには、パラメーターなしのコンストラクターを使用するだけです。