Windows 레지스트리를 사용하여 응용 프로그램 별 상태를 저장할 수도 있습니다. 레지스트리에는 사용자 별 및 컴퓨터 별 키가 있으며 두 키 중 하나 또는 두 키를 사용할 수 있습니다. 예를 들어 일부 사용자는 레지스트리를 사용하여 이탈시 앱 창의 위치와 크기를 저장합니다. 그런 다음 앱을 다시 시작하면 마지막으로 알려진 크기에 따라 창을 배치하고 크기를 지정할 수 있습니다. 이것은 레지스트리에 저장할 수있는 상태의 작은 예제입니다.
이렇게하려면 저장 및 검색을 위해 다른 API를 사용하십시오. 특히 SetValue 및 GetValue는 Microsoft.Win32.RegistryKey 클래스를 호출합니다. 복잡한 상태를 레지스트리에 유지하는 데 유용한 라이브러리가있을 수 있습니다. 간단한 경우 (몇 개의 문자열과 숫자)라면 쉽게 할 수 있습니다.
private static string _AppRegyPath = "Software\\Vendor Name\\Application Name";
public Microsoft.Win32.RegistryKey AppCuKey
{
get
{
if (_appCuKey == null)
{
_appCuKey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(_AppRegyPath, true);
if (_appCuKey == null)
_appCuKey = Microsoft.Win32.Registry.CurrentUser.CreateSubKey(_AppRegyPath);
}
return _appCuKey;
}
set { _appCuKey = null; }
}
private void RetrieveAndApplyState()
{
string s = (string)AppCuKey.GetValue("textbox1Value");
if (s != null) this.textbox1.Text = s;
s = (string)AppCuKey.GetValue("Geometry");
if (!String.IsNullOrEmpty(s))
{
int[] p = Array.ConvertAll<string, int>(s.Split(','),
new Converter<string, int>((t) => { return Int32.Parse(t); }));
if (p != null && p.Length == 4)
{
this.Bounds = ConstrainToScreen(new System.Drawing.Rectangle(p[0], p[1], p[2], p[3]));
}
}
}
private void SaveStateToRegistry()
{
AppCuKey.SetValue("textbox1Value", this.textbox1.Text);
int w = this.Bounds.Width;
int h = this.Bounds.Height;
int left = this.Location.X;
int top = this.Location.Y;
AppCuKey.SetValue("Geometry", String.Format("{0},{1},{2},{3}", left, top, w, h);
}
private System.Drawing.Rectangle ConstrainToScreen(System.Drawing.Rectangle bounds)
{
Screen screen = Screen.FromRectangle(bounds);
System.Drawing.Rectangle workingArea = screen.WorkingArea;
int width = Math.Min(bounds.Width, workingArea.Width);
int height = Math.Min(bounds.Height, workingArea.Height);
// mmm....minimax
int left = Math.Min(workingArea.Right - width, Math.Max(bounds.Left, workingArea.Left));
int top = Math.Min(workingArea.Bottom - height, Math.Max(bounds.Top, workingArea.Top));
return new System.Drawing.Rectangle(left, top, width, height);
}
그 코드는 Microsoft.Win32.Registry.CurrentUser를 사용하고, 그래서 설정하고 사용자 별 응용 프로그램 설정을 검색합니다. 컴퓨터 전체 상태를 설정하거나 검색하는 경우 Microsoft.Win32.Registry.LocalMachine이 필요합니다.
그리고 구성 파일에 대한 사용 권한을 허용해야합니다. App.exe.config는 관리자에게만 쓸 수 있어야합니다. – Richard
감사합니다.Properties.Settings.Default에서 설정을 가져 오려면 어떤 섹션이 필요합니까? –
나는 당신의 질문을 충분히 읽지 못했다. 필자가 제안하는 방법은 구성 파일을 일반적으로 변경하는 것입니다. 어셈블리 범위 설정을 변경하는 또 다른 (더 나은) 방법을 보여주기 위해 내 대답을 업데이트했습니다. –