簡體   English   中英

在Form2中從Form1調用控件

[英]Calling a control from form1 in form2

我必須將類之一是Form1.cs和一個是Form2.cs

在form1.cs中,我有一個tabControl1,當我單擊FORM2.cs中的按鈕時,我想向tabcontrol1(form1)添加一個標簽頁

這可能嗎

當我離開Form2時,我寫了一個包含任何內容的文本文件。 (僅檢查存在的事實。不讀取任何內容,但我想它的內容可用於更新Form1上的文本框。)這會將Form1返回到屏幕。 我在Form1中有一個使用5秒間隔的計時器。 計時器檢查是否存在用Form2編寫的文件。 如果存在,它將被刪除,刪除(文件的)之后的代碼將使用任何必要的步驟來更新Form1。

tabControl1公開為form1的公共屬性。

使用事件和委托,我的意思是公開Form2中的某些事件,並且當Form1調用Form2時,使Form1關聯到Form2的公開事件。 當您單擊Form2中的某些內容時,引發這些事件。 Form1中的事件處理程序被調用/執行,然后您可以在那里更新UI組件。

下面的代碼應該給你一個提示:

 class MyClass
{
    public delegate void CustomDelegate();
    public event CustomDelegate CustomEvent;

    public void RaiseAnEvent()
    {
        CustomEvent();
    }
}

sealed class Program 
{


    static void Main()
    {

        MyClass ms = new MyClass();

        ms.CustomEvent += new MyClass.CustomDelegate(ms_CustomEvent);
        ms.RaiseAnEvent();


        Console.ReadLine();
    }

    static void ms_CustomEvent()
    {
        Console.WriteLine("Event invoked");
    }
}

連接事件的示例:

檔案:Form2.cs

using System;
using System.Windows.Forms;

namespace SO_Suffix
{
    public partial class Form2 : Form
    {
        //<  The delegate needs to be defined as public in the form that 
        //<  is raising the event...
        public delegate void ButtonClickedOnForm2 (object sender, EventArgs e); 

        public Form2()
        {
            InitializeComponent();
            this.button1.Click += new System.EventHandler(this.Button1_Click);
        }

            //<  Capture the click event from the button on Form2, and raise an event
        void Button1_Click(object sender, EventArgs e)
        {
            ButtonClicked(this, e);
        }

        public event ButtonClickedOnForm2 ButtonClicked;
    }
}

Form1.cs:現在只需訂閱該事件

using System;
using System.Windows.Forms;

namespace SO_Suffix
{
    public partial class Form1 : Form
    {
        Form2 form2 = new Form2();

        public Form1()
        {
            InitializeComponent();
             //<  subscribe to the custom event from form2 and set which function to delegate it to ( form2_ButtonClicked )         
            form2.ButtonClicked += new Form2.ButtonClickedOnForm2(form2_ButtonClicked);
            form2.Show();
        }

        private void form2_ButtonClicked(object sender, EventArgs e)
        {
            this.Controls.Add(new Button());
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM