从Registry中恢复表单大小和位置的位置

时间:2015-01-05 16:02:09

标签: c#

我使用以下代码保存表单大小和位置:

    string keyName = string.Format("Software\\{0}\\Position", def.APPNAME);
    using (RegistryKey rk = Registry.CurrentUser.CreateSubKey(keyName)) {
        rk.SetValue("width", this.Width.ToString());
        rk.SetValue("height", this.Height.ToString());
        rk.SetValue("left", this.Left.ToString());
        rk.SetValue("top", this.Top.ToString());
        rk.SetValue("windowstate", this.WindowState.ToString());
    }

我尝试使用此代码恢复它:

    string keyName = string.Format("Software\\{0}\\Position", def.APPNAME);
    using (RegistryKey rk = Registry.CurrentUser.OpenSubKey(keyName, false)) {
        this.Width = (int)rk.GetValue("width");
        this.Height = (int) rk.GetValue("height");
        this.Left = (int) rk.GetValue("left");
        this.Top = (int) rk.GetValue("top");
    }

但我无法弄清楚将它放在哪里才能让它发挥作用。我试过构造函数,表单Load事件,表单OnLoad事件和表单OnCreateControl事件。

在构造函数中,在InitializeComponent()之后,我将收到一条错误,指出System.InvalidCastException:指定的强制转换无效。

在表单Load事件中,表单OnLoad事件和表单OnCreateControl事件没有任何反应。

但如果我直接输入一些值,它将起作用:

    this.Size = new Size(1000,600);

但是,只有我注释掉恢复设置部分!

我应该在哪里放置代码,如何让代码按照我的意愿运行?

1 个答案:

答案 0 :(得分:3)

密切关注System.InvalidCastException。您将值String存储在注册表中,但在阅读时期望它们为int

此代码可以使用吗?

(int)"600"

当然不是。

您应该使用Int32.ParseInt32.TryParseConvert.ToInt32而不是投放到int

object v = rk.GetValue("width");
if (v != null)
{
    //TryParse would be even better.
    this.Width = Int32.Parse((string)v);
}
相关问题