您还可以使用 Windows 注册表来存储应用特定的状态。注册表中有每个用户和每个机器的密钥 - 您可以使用其中一个或两个。例如,有些人在退出时使用注册表来存储应用程序窗口的位置和大小。然后,当应用程序重新启动时,您可以根据上次已知的大小来定位和调整窗口大小。这是您可以在注册表中存储的那种状态的一个小例子。
为此,您将使用不同的 API 进行存储和检索。特别是 Microsoft.Win32.RegistryKey 类上的 SetValue 和 GetValue 调用。可能有一些库有助于将复杂状态保存到注册表。如果您有简单的案例(一些字符串和数字),那么您自己就可以轻松完成。
private static string _AppRegyPath = "Software\\Vendor Name\\Application Name";
public Microsoft.Win32.RegistryKey AppCuKey
{
get
{
if (_appCuKey == null)
{
_appCuKey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(_AppRegyPath, true);
if (_appCuKey == null)
_appCuKey = Microsoft.Win32.Registry.CurrentUser.CreateSubKey(_AppRegyPath);
}
return _appCuKey;
}
set { _appCuKey = null; }
}
private void RetrieveAndApplyState()
{
string s = (string)AppCuKey.GetValue("textbox1Value");
if (s != null) this.textbox1.Text = s;
s = (string)AppCuKey.GetValue("Geometry");
if (!String.IsNullOrEmpty(s))
{
int[] p = Array.ConvertAll<string, int>(s.Split(','),
new Converter<string, int>((t) => { return Int32.Parse(t); }));
if (p != null && p.Length == 4)
{
this.Bounds = ConstrainToScreen(new System.Drawing.Rectangle(p[0], p[1], p[2], p[3]));
}
}
}
private void SaveStateToRegistry()
{
AppCuKey.SetValue("textbox1Value", this.textbox1.Text);
int w = this.Bounds.Width;
int h = this.Bounds.Height;
int left = this.Location.X;
int top = this.Location.Y;
AppCuKey.SetValue("Geometry", String.Format("{0},{1},{2},{3}", left, top, w, h);
}
private System.Drawing.Rectangle ConstrainToScreen(System.Drawing.Rectangle bounds)
{
Screen screen = Screen.FromRectangle(bounds);
System.Drawing.Rectangle workingArea = screen.WorkingArea;
int width = Math.Min(bounds.Width, workingArea.Width);
int height = Math.Min(bounds.Height, workingArea.Height);
// mmm....minimax
int left = Math.Min(workingArea.Right - width, Math.Max(bounds.Left, workingArea.Left));
int top = Math.Min(workingArea.Bottom - height, Math.Max(bounds.Top, workingArea.Top));
return new System.Drawing.Rectangle(left, top, width, height);
}
该代码使用 Microsoft.Win32.Registry.CurrentUser,因此它设置和检索用户特定的应用设置。如果要设置或检索计算机范围的状态,则需要 Microsoft.Win32.Registry.LocalMachine。