从注册表恢复表单大小和位置的位置

本文关键字:位置 注册表 恢复 表单 | 更新日期: 2023-09-27 18:36:21

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

    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");
    }

但是我不知道在哪里放置它才能让它工作。我已经尝试了构造函数,表单加载事件,表单OnLoad事件和表单OnCreateControl事件。

在构造函数中,在 InitializeComponent() 之后,我会得到一个错误,说 System.InvalidCastException:指定的强制转换无效。

在窗体加载事件中,窗体 OnLoad 事件和窗体 OnCreateControl 事件没有任何反应。

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

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

但前提是我注释掉还原设置部分!

应该将代码放在哪里,如何让代码按我想要的方式工作?

从注册表恢复表单大小和位置的位置

密切关注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);
}