65.9K
CodeProject 正在变化。 阅读更多。
Home

自动持久化窗体设置的类

starIconstarIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIcon

2.33/5 (9投票s)

2003年10月29日

1分钟阅读

viewsIcon

41996

downloadIcon

1043

这个类可以自动保存表单的设置。

引言

Windows 表单的一个常见需求是记住表单的最后位置、大小和状态。一种方法是在表单加载和关闭时调用一个函数。我决定以面向对象的方式来做。如果你的表单继承了这个类,它将自动加载和保存表单设置;左侧、顶部、高度、宽度和状态;到一个 .config 文件中。

使用代码

在 C# 项目中使用这个类

  • 将 "PersistentForm.cs" 类添加到你的项目中。
  • 在表单代码的顶部,将 "using KrugismSamples" 添加到引用列表中。
  • 更改
    public class Form1 : System.Windows.Forms.Form

    to

    public class Form1 : PersistentForm

就完成了!当表单加载时,保存的值将被设置到表单上。当表单关闭时,设置将被保存。

在 VB.NET 项目中使用这个类

  • 在你的 VB 解决方案中添加一个新的现有项目,并浏览到 "PersistentForm.csproj" 文件。
  • 在“添加引用”的“项目”选项卡中,添加对 PersistentForm 类的引用。
  • 在源代码的顶部添加 "Imports KrugismSamples"。
  • 更改
  • Inherits System.Windows.Forms.Form

    to

    Inherits PersistentForm

就完成了!当表单加载时,保存的值将被设置到表单上。当表单关闭时,设置将被保存。

概述

这个类非常简单明了。它只是继承了 Windows.Forms.Form 类。然后它重写了 OnCreateControl() OnClosing() 事件。通过重写基本事件,无需向表单添加额外的代码。(LoadSettings() SaveSettings() 代码未在此处显示。)

public class PersistentForm : System.Windows.Forms.Form
{
    public PersistentForm()
    {
    }
    protected override void OnCreateControl()
    {
        LoadSettings();     // Load the saved settings from the file
        base.OnCreateControl ();
    }
   
    protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
    {
        SaveSettings();        // Save the settings to the file
        base.OnClosing(e);
    }
}

历史

  • 2003-10-30 - 为完整性而编辑
  • 2003-10-29 - 初始发布
© . All rights reserved.