當用戶關閉應用程序時,我想保存主應用程序屏幕的一些屬性,例如左側和頂部座標,寬度,長度,最大化,最小化以及其他一些狀態信息。然後,這些將在下次啓動繪製和定位應用主屏幕等C#應用程序狀態持久性 - 如何去解決它?
什麼是做到這一點的最好方法是什麼?數據應該存儲在何處,以何種格式存儲?
謝謝。
當用戶關閉應用程序時,我想保存主應用程序屏幕的一些屬性,例如左側和頂部座標,寬度,長度,最大化,最小化以及其他一些狀態信息。然後,這些將在下次啓動繪製和定位應用主屏幕等C#應用程序狀態持久性 - 如何去解決它?
什麼是做到這一點的最好方法是什麼?數據應該存儲在何處,以何種格式存儲?
謝謝。
可能不是最好的,但定義一個包含這些屬性和XML序列化這一個文件,一個新的類。在加載應用程序時,查找該文件並將其反序列化(如果存在)。
或者,可以通過這個序列化到用戶特定的獨立存儲,使不同用戶的設置不衝突。
最簡單的方法是使用Properties.Settings
。
鏈接:
Using settings in WPF (or how to store/retrieve window pos and loc) Saving window size and location in WPF and WinForms (uses some P/Invoke)
但是,如果你想存儲許多不同的窗口馬修·麥克唐納建議你創建一個存儲爲您傳遞任何窗口的位置的輔助類,使用數據包含該窗口名稱的註冊表項。
public class WindowPositionHelper
{
public static string RegPath = "Software\\MyApp\\WindowBounds\\";
public static void SaveSize(Window win)
{
// Create or retrieve a reference to a key where the settings
// will be stored.
RegistryKey key;
key = Registry.CurrentUser.CreateSubKey(RegPath + win.Name);
key.SetValue("Bounds", win.RestoreBounds.ToString());
key.SetValue("Bounds",
win.RestoreBounds.ToString(CultureInfo.InvariantCulture));
}
public static void SetSize(Window win)
{
RegistryKey key;
key = Registry.CurrentUser.OpenSubKey(RegPath + win.Name);
if (key != null)
{
Rect bounds = Rect.Parse(key.GetValue("Bounds").ToString());
win.Top = bounds.Top;
win.Left = bounds.Left;
// Restore the size only for a manually sized
// window.
if (win.SizeToContent == SizeToContent.Manual)
{
win.Width = bounds.Width;
win.Height = bounds.Height;
}
}
}
}
另一種方法是亞當創建自定義序列化類,將包含你需要存儲,並與他們操縱翻過你的應用程序的所有生命週期的所有屬性說。
註冊表是邪惡的;) – 2010-07-29 15:07:42
這只是其中一種方法。開發人員將決定如何使用各種存儲和加載設置。 – 2010-07-29 15:09:39
有趣的想法。謝謝。 – 2010-07-29 14:44:35