>백엔드 개발 >C++ >대리인과 이벤트 또는 생성자를 사용하여 Windows Forms 간에 변수를 전달하는 방법은 무엇입니까?

대리인과 이벤트 또는 생성자를 사용하여 Windows Forms 간에 변수를 전달하는 방법은 무엇입니까?

Barbara Streisand
Barbara Streisand원래의
2025-01-03 21:34:39171검색

How to Pass Variables Between Windows Forms Using Delegates and Events or Constructors?

대리인과 이벤트를 사용하여 Windows Forms 양식 간에 변수 전달

이 시나리오에서는 기본 양식과 "설정" 하위 항목이 있습니다. form에서 변수를 자식 폼에 전달하는 일반적인 접근 방식은 대리자를 사용하는 것입니다. events.

1단계: 대리인 및 이벤트 초기화

기본 양식에서 데이터 전송을 처리할 대리인과 이벤트를 생성합니다.

public partial class MainForm : Form
{
    /// <summary>
    /// Delegate to send data between forms
    /// </summary>
    public delegate void PageInfoHandler(object sender, PageInfoEventArgs e);

    /// <summary>
    /// Event of the delegate
    /// </summary>
    public event PageInfoHandler PageInfoRetrieved;
}

2단계: 이벤트에 변수 전달 핸들러

기본 양식에서 "설정" 버튼을 클릭하면 전달하려는 변수로 이벤트 인수 인스턴스를 생성하고 이벤트를 발생시킵니다.

private void toolStripBtnSettings_Click(object sender, EventArgs e)
{
    PageInfoEventArgs args = new PageInfoEventArgs(SomeString);
    this.OnPageInfoRetrieved(args);

    SettingsForm settingsForm = new SettingsForm();
    settingsForm.ShowDialog();
}

3단계: 하위 양식에서 변수 검색

"설정" 양식에서 해당 이벤트 핸들러를 재정의하여 이벤트를 생성합니다.

public partial class SettingsForm : Form
{
    protected override void OnShown(EventArgs e)
    {
        base.OnShown(e);

        // Retrieve the event arguments
        PageInfoEventArgs args = this.Tag as PageInfoEventArgs;
        if (args != null)
        {
            // Access the passed variable
            string receivedText = args.PageInfo;
        }
    }
}

생성자를 사용하여 변수 전달

또는 변수를 자식 생성자에 직접 전달할 수도 있습니다. form:

public partial class SettingsForm : Form
{
    private string receivedText;

    public SettingsForm(string text)
    {
        this.receivedText = text;
    }
}

이 경우 변수를 사용하여 하위 양식 인스턴스를 생성합니다. 인수:

SettingsForm settingsForm = new SettingsForm(SomeString);

위 내용은 대리인과 이벤트 또는 생성자를 사용하여 Windows Forms 간에 변수를 전달하는 방법은 무엇입니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.