ApplicationSettingsBase 클래스

정의

Window Forms 애플리케이션에서 애플리케이션 설정 기능을 구현하기 위해 구체적인 파생 래퍼 클래스의 기본 클래스 역할을 합니다.

public ref class ApplicationSettingsBase abstract : System::Configuration::SettingsBase, System::ComponentModel::INotifyPropertyChanged
public abstract class ApplicationSettingsBase : System.Configuration.SettingsBase, System.ComponentModel.INotifyPropertyChanged
type ApplicationSettingsBase = class
    inherit SettingsBase
    interface INotifyPropertyChanged
Public MustInherit Class ApplicationSettingsBase
Inherits SettingsBase
Implements INotifyPropertyChanged
상속
ApplicationSettingsBase
구현

예제

다음 코드 예제에서는 기본 폼의 특성을 유지 하려면 애플리케이션 설정의 사용을 보여 줍니다: 위치, 크기, 배경색 및 제목 표시줄 텍스트입니다. 이러한 특성은 모두에서 단일 애플리케이션 설정 속성으로 유지 됩니다는 FormSettings 이라는 클래스가 FormLocation, FormSize, FormBackColorFormText, 각각. 및 SizeFormText 제외한 모든 항목은 연결된 양식 속성에 바인딩된 데이터이며 를 사용하여 DefaultSettingValueAttribute기본 설정 값을 적용합니다.

양식에는 다음과 같은 이름과 함수가 있는 4개의 자식 컨트롤이 포함되어 있습니다.

  • 공통 대화 상자를 표시하는 데 사용되는 라는 btnBackColor 단추입니다.

  • 이라는 단추가 btnReloadReload 애플리케이션 설정 합니다.

  • 이라는 단추가 btnResetReset 애플리케이션 설정 합니다.

  • 프로그램에 대한 상태 정보를 표시하는 데 사용되는 라는 tbStatus 텍스트 상자입니다.

애플리케이션의 모든 실행 후 있음을, 폼의 제목 텍스트에 마침표 문자가 추가 됩니다.

이 코드 예제에는 라는 클래스가 있는 ColorDialog Form과 StatusStrip 라는 colorDialog1tbStatus컨트롤이 ToolStripStatusLabel 필요합니다. 또한 , btnResetbtnBackColor라는 btnReloadButton 개의 개체가 필요합니다.


#using <System.dll>
#using <System.Drawing.dll>
#using <System.Windows.Forms.dll>

using namespace System;
using namespace System::ComponentModel;
using namespace System::Drawing;
using namespace System::Configuration;
using namespace System::Windows::Forms;

namespace AppSettingsSample
{
    //Application settings wrapper class
    ref class FormSettings sealed: public ApplicationSettingsBase
    {
    public:
        [UserScopedSettingAttribute()]
        property String^ FormText
        {
            String^ get()
            {
                return (String^)this["FormText"];
            }
            void set( String^ value )
            {
                this["FormText"] = value;
            }
        }

    public:
        [UserScopedSettingAttribute()]
        [DefaultSettingValueAttribute("0, 0")]
        property Point FormLocation
        {
            Point get()
            {
                return (Point)(this["FormLocation"]);
            }
            void set( Point value )
            {
                this["FormLocation"] = value;
            }
        }

    public:
        [UserScopedSettingAttribute()]
        [DefaultSettingValueAttribute("225, 200")]
        property Size FormSize
        {
            Size get()
            {
                return (Size)this["FormSize"];
            }
            void set( Size value )
            {
                this["FormSize"] = value;
            }
        }

    public:
        [UserScopedSettingAttribute()]
        [DefaultSettingValueAttribute("LightGray")]
        property Color FormBackColor
        {
            Color get()
            {
                return (Color)this["FormBackColor"];
            }
            void set(Color value)
            {
                this["FormBackColor"] = value;
            }
        }

    };

    ref class AppSettingsForm : Form
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
    private:
        System::ComponentModel::IContainer^ components;

        /// <summary>
        /// Clean up any resources being used. The Dispose(true) 
        /// pattern for embedded objects is implemented with this
        /// code that just contains a destructor 
        /// </summary>
    public:
        ~AppSettingsForm()
        {
            if (components != nullptr)
            {
                delete components;
            }
        }

#pragma region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
    private:
        void InitializeComponent()
        {
            this->components = nullptr;
            this->colorDialog = gcnew System::Windows::Forms::ColorDialog();
            this->backColorButton = gcnew System::Windows::Forms::Button();
            this->resetButton = gcnew System::Windows::Forms::Button();
            this->statusDisplay = gcnew System::Windows::Forms::TextBox();
            this->reloadButton = gcnew System::Windows::Forms::Button();
            this->SuspendLayout();
            //
            // backColorButton
            //
            this->backColorButton->Location = System::Drawing::Point(26, 24);
            this->backColorButton->Name = "backColorButton";
            this->backColorButton->Size = System::Drawing::Size(159, 23);
            this->backColorButton->TabIndex = 0;
            this->backColorButton->Text = "Change Background Color";
            this->backColorButton->Click += gcnew System::EventHandler
                (this,&AppSettingsForm::BackColorButton_Click);
            //
            // resetButton
            //
            this->resetButton->Location = System::Drawing::Point(26, 90);
            this->resetButton->Name = "resetButton";
            this->resetButton->Size = System::Drawing::Size(159, 23);
            this->resetButton->TabIndex = 1;
            this->resetButton->Text = "Reset to Defaults";
            this->resetButton->Click += gcnew System::EventHandler
                (this,&AppSettingsForm::ResetButton_Click);
            //
            // statusDisplay
            //
            this->statusDisplay->Location = System::Drawing::Point(26, 123);
            this->statusDisplay->Name = "statusDisplay";
            this->statusDisplay->Size = System::Drawing::Size(159, 20);
            this->statusDisplay->TabIndex = 2;
            //
            // reloadButton
            //
            this->reloadButton->Location = System::Drawing::Point(26, 57);
            this->reloadButton->Name = "reloadButton";
            this->reloadButton->Size = System::Drawing::Size(159, 23);
            this->reloadButton->TabIndex = 3;
            this->reloadButton->Text = "Reload from Storage";
            this->reloadButton->Click += gcnew System::EventHandler
                (this,&AppSettingsForm::ReloadButton_Click);
            //
            // AppSettingsForm
            //
            this->ClientSize = System::Drawing::Size(217, 166);
            this->Controls->Add(this->reloadButton);
            this->Controls->Add(this->statusDisplay);
            this->Controls->Add(this->resetButton);
            this->Controls->Add(this->backColorButton);
            this->Name = "AppSettingsForm";
            this->Text = "App Settings";
            this->FormClosing += gcnew
                System::Windows::Forms::FormClosingEventHandler
                (this,&AppSettingsForm::AppSettingsForm_FormClosing);
            this->Load += gcnew System::EventHandler(this,
                &AppSettingsForm::AppSettingsForm_Load);
            this->ResumeLayout(false);
            this->PerformLayout();

        }

#pragma endregion

    private:
        System::Windows::Forms::ColorDialog^ colorDialog;

        System::Windows::Forms::Button^ backColorButton;

        System::Windows::Forms::Button^ resetButton;

        System::Windows::Forms::TextBox^ statusDisplay;

        System::Windows::Forms::Button^ reloadButton;



        FormSettings ^ formSettings;

    public:
        AppSettingsForm()
        {
            formSettings = gcnew FormSettings;
            InitializeComponent();
        }

    private:
        void AppSettingsForm_Load(Object^ sender, EventArgs^ e)
        {
            //Associate settings property event handlers.
            formSettings->SettingChanging += gcnew SettingChangingEventHandler(
                this, &AppSettingsForm::FormSettings_SettingChanging);
            formSettings->SettingsSaving += gcnew SettingsSavingEventHandler(
                this,&AppSettingsForm::FormSettings_SettingsSaving);

            //Data bind settings properties with straightforward associations.
            Binding^ backColorBinding = gcnew Binding("BackColor", 
                formSettings, "FormBackColor", true, 
                DataSourceUpdateMode::OnPropertyChanged);
            this->DataBindings->Add(backColorBinding);
            Binding^ sizeBinding = gcnew Binding("Size", formSettings,
                "FormSize", true, DataSourceUpdateMode::OnPropertyChanged);
            this->DataBindings->Add(sizeBinding);
            Binding^ locationBinding = gcnew Binding("Location", formSettings,
                "FormLocation", true, DataSourceUpdateMode::OnPropertyChanged);
            this->DataBindings->Add(locationBinding);

            //For more complex associations, manually assign associations.
            String^ savedText = formSettings->FormText;
            //Since there is no default value for FormText.
            if (savedText != nullptr)
            {
                this->Text = savedText;
            }
        }

    private:
        void AppSettingsForm_FormClosing(Object^ sender,
            FormClosingEventArgs^ e)
        {
            //Synchronize manual associations first.
            formSettings->FormText = this->Text + '.';
            formSettings->Save();
        }

    private:
        void BackColorButton_Click(Object^ sender, EventArgs^ e)
        {
            if (::DialogResult::OK == colorDialog->ShowDialog())
            {
                Color color = colorDialog->Color;
                this->BackColor = color;
            }
        }

    private:
        void ResetButton_Click(Object^ sender, EventArgs^ e)
        {
            formSettings->Reset();
            this->BackColor = SystemColors::Control;
        }

    private:
        void ReloadButton_Click(Object^ sender, EventArgs^ e)
        {
            formSettings->Reload();
        }

    private:
        void FormSettings_SettingChanging(Object^ sender,
            SettingChangingEventArgs^ e)
        {
            statusDisplay->Text = e->SettingName + ": " + e->NewValue;
        }

    private:
        void FormSettings_SettingsSaving(Object^ sender,
            CancelEventArgs^ e)
        {
            //Should check for settings changes first.
            ::DialogResult^ dialogResult = MessageBox::Show(
                "Save current values for application settings?",
                "Save Settings", MessageBoxButtons::YesNo);
            if (::DialogResult::No == dialogResult)
            {
                e->Cancel = true;
            }
        }
    };
partial class Form1 : Form
{
    private FormSettings frmSettings1 = new FormSettings();

    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        this.FormClosing += new FormClosingEventHandler(Form1_FormClosing);

        //Associate settings property event handlers.
        frmSettings1.SettingChanging += new SettingChangingEventHandler(
                                            frmSettings1_SettingChanging);
        frmSettings1.SettingsSaving += new SettingsSavingEventHandler(
                                            frmSettings1_SettingsSaving);

        //Data bind settings properties with straightforward associations.
        Binding bndBackColor = new Binding("BackColor", frmSettings1,
            "FormBackColor", true, DataSourceUpdateMode.OnPropertyChanged);
        this.DataBindings.Add(bndBackColor);
        Binding bndLocation = new Binding("Location", frmSettings1,
            "FormLocation", true, DataSourceUpdateMode.OnPropertyChanged);
        this.DataBindings.Add(bndLocation);

        // Assign Size property, since databinding to Size doesn't work well.
         this.Size = frmSettings1.FormSize;

        //For more complex associations, manually assign associations.
        String savedText = frmSettings1.FormText;
        //Since there is no default value for FormText.
        if (savedText != null)
            this.Text = savedText;
    }

    private void Form1_FormClosing(object sender, FormClosingEventArgs e)
    {
        //Synchronize manual associations first.
        frmSettings1.FormText = this.Text + '.';
        frmSettings1.FormSize = this.Size;
        frmSettings1.Save();
    }

    private void btnBackColor_Click(object sender, EventArgs e)
    {
        if (DialogResult.OK == colorDialog1.ShowDialog())
        {
            Color c = colorDialog1.Color;
            this.BackColor = c;
        }
    }

    private void btnReset_Click(object sender, EventArgs e)
    {
        frmSettings1.Reset();
        this.BackColor = SystemColors.Control;
    }

    private void btnReload_Click(object sender, EventArgs e)
    {
        frmSettings1.Reload();
    }

    void frmSettings1_SettingChanging(object sender, SettingChangingEventArgs e)
    {
        tbStatus.Text = e.SettingName + ": " + e.NewValue;
    }

    void frmSettings1_SettingsSaving(object sender, CancelEventArgs e)
    {
        //Should check for settings changes first.
        DialogResult dr = MessageBox.Show(
                        "Save current values for application settings?",
                        "Save Settings", MessageBoxButtons.YesNo);
        if (DialogResult.No == dr)
        {
            e.Cancel = true;
        }
    }
}

//Application settings wrapper class
sealed class FormSettings : ApplicationSettingsBase
{
    [UserScopedSettingAttribute()]
    public String FormText
    {
        get { return (String)this["FormText"]; }
        set { this["FormText"] = value; }
    }

    [UserScopedSettingAttribute()]
    [DefaultSettingValueAttribute("0, 0")]
    public Point FormLocation
    {
        get { return (Point)(this["FormLocation"]); }
        set { this["FormLocation"] = value; }
    }

    [UserScopedSettingAttribute()]
    [DefaultSettingValueAttribute("225, 200")]
    public Size FormSize
    {
        get { return (Size)this["FormSize"]; }
        set { this["FormSize"] = value; }
    }

    [UserScopedSettingAttribute()]
    [DefaultSettingValueAttribute("LightGray")]
    public Color FormBackColor
    {
        get { return (Color)this["FormBackColor"]; }
        set { this["FormBackColor"] = value; }
    }
}
Imports System.Configuration
Imports System.ComponentModel

Public Class Form1

    Private WithEvents frmSettings1 As New FormSettings

    Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs) _
            Handles MyBase.Load
        'Settings property event handlers are associated through WithEvents 
        '  and Handles combination.

        'Data bind settings properties with straightforward associations.
        Dim bndBackColor As New Binding("BackColor", frmSettings1, "FormBackColor", _
                True, DataSourceUpdateMode.OnPropertyChanged)
        Me.DataBindings.Add(bndBackColor)
        Dim bndLocation As New Binding("Location", frmSettings1, "FormLocation", _
                True, DataSourceUpdateMode.OnPropertyChanged)
        Me.DataBindings.Add(bndLocation)

        ' Assign Size property, since databinding to Size doesn't work well.
        Me.Size = frmSettings1.FormSize

        'For more complex associations, manually assign associations.
        Dim savedText As String = frmSettings1.FormText
        'Since there is no default value for FormText.
        If (savedText IsNot Nothing) Then
            Me.Text = savedText
        End If
    End Sub

    Private Sub Form1_FormClosing_1(ByVal sender As Object, ByVal e As _
            FormClosingEventArgs) Handles MyBase.FormClosing
        'Synchronize manual associations first.
        frmSettings1.FormText = Me.Text + "."c

        ' Save size settings manually.
        frmSettings1.FormSize = Me.Size

        frmSettings1.Save()
    End Sub

    Private Sub btnBackColor_Click(ByVal sender As Object, ByVal e As EventArgs) _
            Handles btnBackColor.Click
        If System.Windows.Forms.DialogResult.OK = colorDialog1.ShowDialog() Then
            Dim c As Color = colorDialog1.Color
            Me.BackColor = c
        End If
    End Sub

    Private Sub btnReset_Click(ByVal sender As Object, ByVal e As EventArgs) _
            Handles btnReset.Click
        frmSettings1.Reset()
        Me.BackColor = SystemColors.Control
    End Sub

    Private Sub btnReload_Click(ByVal sender As Object, ByVal e As EventArgs) _
            Handles btnReload.Click
        frmSettings1.Reload()
    End Sub

    Private Sub frmSettings1_SettingChanging(ByVal sender As Object, ByVal e As _
            SettingChangingEventArgs) Handles frmSettings1.SettingChanging
        tbStatus.Text = e.SettingName & ": " & e.NewValue.ToString
    End Sub

    Private Sub frmSettings1_SettingsSaving(ByVal sender As Object, ByVal e As _
            CancelEventArgs) Handles frmSettings1.SettingsSaving
        'Should check for settings changes first.
        Dim dr As DialogResult = MessageBox.Show( _
            "Save current values for application settings?", "Save Settings", _
            MessageBoxButtons.YesNo)
        If (System.Windows.Forms.DialogResult.No = dr) Then
            e.Cancel = True
        End If
    End Sub
End Class

'Application settings wrapper class. This class defines the settings we intend to use in our application.
NotInheritable Class FormSettings
    Inherits ApplicationSettingsBase

    <UserScopedSettingAttribute()> _
    Public Property FormText() As String
        Get
            Return CStr(Me("FormText"))
        End Get
        Set(ByVal value As String)
            Me("FormText") = value
        End Set
    End Property

    <UserScopedSettingAttribute(), DefaultSettingValueAttribute("0, 0")> _
    Public Property FormLocation() As Point
        Get
            Return CType(Me("FormLocation"), Point)
        End Get
        Set(ByVal value As Point)
            Me("FormLocation") = value
        End Set
    End Property

    <UserScopedSettingAttribute(), DefaultSettingValueAttribute("225, 200")> _
    Public Property FormSize() As Size
        Get
            Return CType(Me("FormSize"), Size)
        End Get
        Set(ByVal value As Size)
            Me("FormSize") = value
        End Set
    End Property

    <UserScopedSettingAttribute(), DefaultSettingValueAttribute("LightGray")> _
    Public Property FormBackColor() As Color
        Get
            Return CType(Me("FormBackColor"), Color)
        End Get
        Set(ByVal value As Color)
            Me("FormBackColor") = value
        End Set
    End Property
End Class

설명

ApplicationSettingsBase 다음과 같은 기능을 추가 합니다 SettingsBase 웹 기반 애플리케이션에서 사용 되는 클래스:

  • 파생된 설정 래퍼 클래스에서 특성을 검색하는 기능입니다. ApplicationSettingsBase 는 나중에 설명한 대로 래퍼 클래스 속성에 사용되는 선언적 모델을 지원합니다.

  • 상위 수준 SaveReload 메서드.

  • 개별 설정의 정확성을 보장하기 위해 처리할 수 있는 추가 유효성 검사 이벤트입니다.

애플리케이션 설정 아키텍처에서 그룹 설정 속성에 액세스 하려면 구체적인 래퍼 클래스를 파생 ApplicationSettingsBase합니다. 래퍼 클래스는 다음과 같은 방법으로 사용자 지정합니다 ApplicationSettingsBase .

  • 액세스할 모든 설정 속성에 대해 해당 강력한 형식의 public 속성이 래퍼 클래스에 추가됩니다. 이 속성은 get 하 고 set 만 읽기/쓰기 애플리케이션 설정에 대 한 접근자를 get 읽기 전용으로 설정에 대 한 접근자입니다.

  • 설정 로밍에 대 한 기본값을 지원 해야 하는지 여부를 설정의 범위 (애플리케이션 또는 사용자) 같은 설정 속성의 특성을 나타내는 래퍼 클래스의 공용 속성에 적절 한 특성을 적용 해야 합니다 설정을 사용 하는 설정 공급자입니다. 각 속성은 또는 UserScopedSettingAttribute를 사용하여 ApplicationScopedSettingAttribute scope 지정해야 합니다. 애플리케이션 범위 설정은 읽기 전용 경우 기본 LocalFileSettingsProvider 사용 됩니다.

클래스는 ApplicationSettingsBase 리플렉션을 사용하여 런타임에 이러한 특성을 검색합니다. 이 정보의 대부분은 스토리지, 지속성 형식 등을 담당하는 설정 공급자 계층으로 전달됩니다.

애플리케이션에 여러 설정 래퍼 클래스가 있는 경우 각 클래스는 설정 그룹을 정의합니다. 각 그룹에는 다음과 같은 특성이 있습니다.

  • 그룹에는 모든 수 또는 유형의 속성 설정이 포함될 수 있습니다.

  • 래퍼 클래스 SettingsGroupNameAttribute를 로 데코레이팅하여 그룹 이름을 명시적으로 설정하지 않으면 이름이 자동으로 생성됩니다.

기본적으로 모든 클라이언트 기반 애플리케이션 사용을 LocalFileSettingsProvider 스토리지를 제공 합니다. 대체 설정 공급자가 필요한 경우 래퍼 클래스 또는 속성을 해당 SettingsProviderAttribute로 데코레이트해야 합니다.

애플리케이션 설정을 사용 하는 방법에 대 한 자세한 내용은 참조 하세요. Windows Forms에 대 한 애플리케이션 설정을합니다.

생성자

ApplicationSettingsBase()

ApplicationSettingsBase 클래스의 인스턴스를 기본 상태로 초기화합니다.

ApplicationSettingsBase(IComponent)

제공된 소유자 구성 요소를 사용하여 ApplicationSettingsBase 클래스의 인스턴스를 초기화합니다.

ApplicationSettingsBase(IComponent, String)

제공된 소유자 구성 요소와 설정 키를 사용하여 ApplicationSettingsBase 클래스의 인스턴스를 초기화합니다.

ApplicationSettingsBase(String)

제공된 설정 키를 사용하여 ApplicationSettingsBase 클래스의 인스턴스를 초기화합니다.

속성

Context

설정 그룹과 연결된 애플리케이션 설정 컨텍스트를 가져옵니다.

IsSynchronized

개체에 대한 액세스가 동기화되어 스레드로부터 안전한지 여부를 나타내는 값을 가져옵니다.

(다음에서 상속됨 SettingsBase)
Item[String]

지정된 애플리케이션 설정 속성의 값을 가져오거나 설정합니다.

Properties

래퍼에 있는 설정 속성의 컬렉션을 가져옵니다.

PropertyValues

속성 값의 컬렉션을 가져옵니다.

Providers

래퍼에서 사용하는 애플리케이션 설정 공급자의 컬렉션을 가져옵니다.

SettingsKey

애플리케이션 설정 그룹의 설정 키를 가져오거나 설정합니다.

메서드

Equals(Object)

지정된 개체가 현재 개체와 같은지 확인합니다.

(다음에서 상속됨 Object)
GetHashCode()

기본 해시 함수로 작동합니다.

(다음에서 상속됨 Object)
GetPreviousVersion(String)

이전 버전의 동일한 애플리케이션에 대한 명명된 설정 속성의 값을 반환합니다.

GetType()

현재 인스턴스의 Type을 가져옵니다.

(다음에서 상속됨 Object)
Initialize(SettingsContext, SettingsPropertyCollection, SettingsProviderCollection)

SettingsBase 개체가 사용하는 내부 속성을 초기화합니다.

(다음에서 상속됨 SettingsBase)
MemberwiseClone()

현재 Object의 단순 복사본을 만듭니다.

(다음에서 상속됨 Object)
OnPropertyChanged(Object, PropertyChangedEventArgs)

PropertyChanged 이벤트를 발생시킵니다.

OnSettingChanging(Object, SettingChangingEventArgs)

SettingChanging 이벤트를 발생시킵니다.

OnSettingsLoaded(Object, SettingsLoadedEventArgs)

SettingsLoaded 이벤트를 발생시킵니다.

OnSettingsSaving(Object, CancelEventArgs)

SettingsSaving 이벤트를 발생시킵니다.

Reload()

영구 스토리지에서 애플리케이션 설정 속성 값을 새로 고칩니다.

Reset()

영구 애플리케이션 설정 값을 해당 기본 속성으로 복원합니다.

Save()

애플리케이션 설정 속성의 현재 값을 저장합니다.

ToString()

현재 개체를 나타내는 문자열을 반환합니다.

(다음에서 상속됨 Object)
Upgrade()

애플리케이션의 최신 설치를 반영하기 위해 애플리케이션 설정을 업데이트합니다.

이벤트

PropertyChanged

애플리케이션 설정 속성의 값이 변경된 후 발생합니다.

SettingChanging

애플리케이션 설정 속성의 값이 변경되기 전에 발생합니다.

SettingsLoaded

애플리케이션 설정이 스토리지에서 검색된 후 발생합니다.

SettingsSaving

값이 데이터 저장소에 저장되기 전에 발생합니다.

적용 대상

추가 정보