导航

为了实现这个效果,起始是想在窗体关闭时把窗体的坐标位置写入注册表或者是ini文件中,当程序启动的时候根据注册表或者ini文件中记录的坐标位置信息来初始化窗体,但是苦于这两种办法没有尝试过,下午就要放年假了,明天的火车,也没时间再去研究注册表或者ini文件,干脆写入config配置文件吧!

1、 首先在项目中添加一个app.config文件(是窗体程序,不是Web哦),在<configuration/>配置节下添加一个<appSettings/>配置节,在该节下添加属性,定义窗体程序的坐标位置值(X,Y)代码如下:

<configuration>

  <appSettings>

    <add key="Form1.X" value="0" />

    <add key="Form1.Y" value="0" />

  </appSettings>

</configuration>

2、 Sub New()过程中重构窗体程序并初始化:此时从配置文件中读取坐标位置值。

Public Sub New()

 

        ' 此调用是 Windows 窗体设计器所必需的。

        InitializeComponent()

 

        ' InitializeComponent() 调用之后添加任何初始化。

 

        Dim configReader As System.Configuration.AppSettingsReader = New System.Configuration.AppSettingsReader()

        Dim x As Integer, y As Integer

        ' 从配置文件中检索值并转化为整型

        x = CType(configReader.GetValue("Form1.X", GetType(System.Int32)), Integer)

        y = CType(configReader.GetValue("Form1.Y", GetType(System.Int32)), Integer)

        ' 使用新的xy设置位置

        Me.Location = New System.Drawing.Point(x, y)

 

        Me.StartPosition = FormStartPosition.Manual

    End Sub

3、 接下来就是要在关闭窗体时保存当前窗体所在的位置,否则下次启动时程序还是不知道上次的位置在什么地方。

Private Sub Form2_FormClosing(ByVal sender As System.Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles MyBase.FormClosing

        Dim Asm As System.Reflection.Assembly = System.Reflection.Assembly.GetExecutingAssembly

        Dim strConfigLoc As String

        strConfigLoc = Asm.Location

 

        '配置文件再应用程序的bin目录,因此需要删除文件名

        Dim strTemp As String

        strTemp = strConfigLoc

        strTemp = System.IO.Path.GetDirectoryName(strConfigLoc)

 

        '为配置文件定义一个FileInfo对象

        Dim FileInfo As System.IO.FileInfo = New System.IO.FileInfo(strTemp & "\test1.exe.config")

 

        '将配置文件读入XML DOM

        Dim XmlDocument As New System.Xml.XmlDocument()

        XmlDocument.Load(FileInfo.FullName)

 

        '找到正确的节点并将它的值改为新的

        Dim Node As System.Xml.XmlNode

        For Each Node In XmlDocument.Item("configuration").Item("appSettings")

            '略过注释

            If Node.Name = "add" Then

                If Node.Attributes.GetNamedItem("key").Value = "Form1.X" Then

                    ' X转化为字符串

                    Node.Attributes.GetNamedItem("value").Value = CType(Me.Location.X, String)

                End If

                If Node.Attributes.GetNamedItem("key").Value = "Form1.Y" Then

                    Node.Attributes.GetNamedItem("value").Value = CType(Me.Location.Y, String)

                End If

            End If

        Next Node

 

        '保存修改过的配置文件

        XmlDocument.Save(FileInfo.FullName)

    End Sub

4、 此时运行程序,关闭程序并重启,发现窗体并没有在上次关闭的位置上显示,因为在初始化过程中,Location属性被StartPosition属性重载了,而StartPosition属性的默认值是WindowsDefault,这意味着窗体的显示位置是由Windows决定的。

5、 为了达到预期的效果,在Sub New过程中重新设置StartPosition属性,这样就好了。

Me.StartPosition = FormStartPosition.Manual

好了,至此我们的任务已经全部完成,我也要准备回家过年了!新年快乐哦!