2011年12月10日 星期六

VB.net 一個簡單的方法來儲存視窗關閉位置

在寫視窗應用程式時,有一個需求是想要每次開啟視窗時,視窗都能記憶住上次關閉時的位置。

通常在視窗上可以設定開啟時的預設選項只有置中比較好用外,其它的方式開啟都會亂跳…根本不知道視窗會開在哪…

這時候就必需透過程式來明白定義出視窗開啟的顯示位置了。

首先,在每次關閉視窗時,當然我們必需要把關閉時的位置記下來,這邊簡單用文字檔方式來儲存關閉時的視窗位置:



'儲存目前畫面位置
Try
If Me.Location.X.ToString > 0 And Me.Location.Y.ToString > 0 Then
Dim filePathLoc As String = System.Windows.Forms.Application.StartupPath & "\Loc.txt"
Dim FileNumLoc As Integer
If System.IO.File.Exists(filePathLoc) = True Then
System.IO.File.Delete(filePathLoc)
End If
FileNumLoc = FreeFile()
FileOpen(FileNumLoc, filePathLoc, OpenMode.Output)
PrintLine(FileNumLoc, Me.Location.X.ToString & "," & Me.Location.Y.ToString & "," & Me.Height.ToString & "," & Me.Width.ToString)
FileClose(FileNumLoc)
End If
Catch ex As Exception
End Try


上面這段程式碼主要是放在 Form_closing 的事件裡面,這樣就可以在每次關閉視窗時,把視窗目前的位置存到該應用程式執行的目錄底下的 Loc.txt 這個檔案裡了。

接下來就是當打開視窗時,我們必需讀取 Loc.txt 裡面的資料,並依照此資料來作視窗的顯示:


'設定畫面顯示位置 - begin
Dim filePath As String = System.Windows.Forms.Application.StartupPath & "\Loc.txt"
Try
Dim loc() As String = My.Computer.FileSystem.ReadAllText(filePath).Split(",")
If loc(0) > System.Windows.Forms.Screen.PrimaryScreen.Bounds.Width Or loc(1) > System.Windows.Forms.Screen.PrimaryScreen.Bounds.Height Then
Me.Location = New Point(0, 0)
Else
Me.Location = New Point(loc(0), loc(1))
End If
Me.Height = loc(2)
Me.Width = loc(3)
Catch ex As Exception
Me.StartPosition = FormStartPosition.CenterScreen
Me.Height = 200
Me.Width = 500
End Try


上面這段程式碼就是放在 Form_load 事件裡的最前面囉…

可以看到程式中讀取了 Loc.txt 這個檔案,並作視窗顯示的位置設定…

這邊會有例外情況就是讀不到 Loc.txt 這個檔案時,也必需另外作處理…就可以把預設的視窗大小等資訊寫在這個部份。

基本上這樣子就完成了記憶視窗關閉位置、大小的設定了。

沒有留言:

張貼留言

留言請留下大名~謝謝。

Related Posts Plugin for WordPress, Blogger...