C# :修改登錄檔,從上次關閉位置啟動窗體
阿新 • • 發佈:2021-02-14
備忘錄
1.首先,手動新增Winform窗體關閉的事件程式碼
右擊窗體,選擇屬性:點選右邊的小閃電標誌
2.雙擊FormClosing事件
3.完善窗體關閉的程式碼
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
RegistryKey point1, point2;
//獲取登錄檔的根節點HKEY_CURRENT_USER
point1 = Registry.CurrentUser;
//再獲取接下來的節點
point2 = point1.CreateSubKey("Software\\MySoft");
try
{
//將當前窗體的X,Y座標儲存在其中
point2.SetValue("1", this.Location.X.ToString());
point2.SetValue("2", this.Location.Y.ToString ());
}
catch (Exception)
{
}
}
上面程式碼的目的是在窗體關閉的時候,讀取一下當前窗體所在的位置,然後儲存在登錄檔中
4.完善窗體載入時的程式碼(下面程式碼的目的是在窗體載入的時候,從登錄檔中讀取上面儲存的座標)
private void Form1_Load(object sender, EventArgs e)
{
RegistryKey point1, point2;
//獲取登錄檔的根節點HKEY_CURRENT_USER
point1 = Registry.CurrentUser;
try
{
//再獲取接下來的節點
point2 = point1.CreateSubKey("Software\\MySoft");
//讀取登錄檔中儲存的資訊,並將當前窗體的座標顯示出來
this.Location = new Point(Convert.ToInt16(point2.GetValue("1")), Convert.ToInt16(point2.GetValue("2")));
}
catch (Exception)
{
}
}