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

VB.NET 2.0 和 Visual Studio 2005 中的应用程序设置

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.62/5 (26投票s)

2005年11月15日

2分钟阅读

viewsIcon

381998

downloadIcon

3347

一篇关于在 VB.NET 2.0 和 Visual Studio 2005 中使用应用程序设置来保存窗体的大小和位置的文章。

引言

.NET 2.0 和 Visual Studio 2005 的一项新功能是将用户的应用程序设置保存到保存在用户桌面配置文件中的 user.config 文件中。

背景

在 .NET 2.0 之前,保存应用程序的用户设置很困难。用户设置必须保存在注册表中、.ini 文件中或自定义文本文件中。现在,可以保存用户的应用程序设置,即使在漫游桌面配置文件中也能随他们一起移动。

要查看非漫游设置,请打开位于 %USERPROFILE%\Local Settings\Application Data\<公司名称>\<appdomainname>_<eid>_<hash>\<verison>\user.configuser.config 文件。

要查看漫游用户设置,请打开位于 %USERPROFILE%\Application Data\<公司名称>\<appdomainname>_<eid>_<hash>\<verison>\user.configuser.config 文件。

使用代码

要将应用程序或用户设置添加到项目,请在解决方案资源管理器窗口中右键单击项目名称,然后单击“属性”。然后,单击左侧选项卡列表中的“设置”。

Sample Image - AppSettings2005.jpg

当设置添加到 Visual Studio 设计器时,将在 My.Settings 命名空间中创建一个公共属性。根据设置的作用域,该属性将是 ReadOnly 或可写的。这允许您以编程方式更改用户设置值并使用 My.Settings.Save() 方法保存它们。

保存设置的第二种方法是在应用程序中启用“在关闭时保存 My.Settings”设置。为此,在解决方案资源管理器窗口中右键单击项目名称,然后单击“属性”。然后,单击左侧选项卡列表中的“应用程序”。

Sample Image - AppSettings2005_save.jpg

要恢复窗体最后保存的尺寸,我们在窗体的 Load 事件中从用户设置中设置窗体的大小和位置。

Private Sub Form1_Load _
    (ByVal sender As Object, ByVal e As System.EventArgs) _
    Handles Me.Load
        'Set textboxes and form name from application and user settings

        'Notice how the application setting property is ReadOnly
        Me.Text = My.Settings.MainFormText

        'Notice how the user settings are writable
        Me.Size = My.Settings.MainFormSize
        Me.Location = My.Settings.MainFormLocation

        Me.txtFormText.Text = My.Settings.MainFormText

        'Show the form now
        Me.Visible = True
    End Sub

在窗体的 FormClosing 事件中,我们将窗体的大小和位置值保存到当前值。

Main form closing

Private Sub Form1_FormClosing _
    (ByVal sender As Object, _
    ByVal e As System.Windows.Forms.FormClosingEventArgs) _
    Handles Me.FormClosing
        Try
            'Set my user settings MainFormSize to the
            'current(Form) 's size
            My.Settings.MainFormSize = Me.Size

            'Set my user setting MainFormLocation to
            'the current form's location
            My.Settings.MainFormLocation = Me.Location

            'Save the user settings so next time the
            'window will be the same size and location
            My.Settings.Save()

            MsgBox("Your settings were saved successfully.", _
            MsgBoxStyle.OkOnly, "Save...")
        Catch ex As Exception
            MsgBox("There was a problem saving your settings.", _
            MsgBoxStyle.Critical, "Save Error...")
        End Try
    End Sub

结论

您可以在 .NET 2.0 中将应用程序和用户设置用于许多用途。请记住,如果您想更改设置,则作用域必须设置为“用户”。

历史

  • 第二次修订 - 移动文本和图像以使文章更具可读性。添加了“结论”部分。
  • 第三次修订 - 更新了 user.config 文件路径,并添加了配置文件和自动退出保存的说明。
© . All rights reserved.