从form2中的form1调用控件

时间:2011-11-10 02:53:07

标签: c# winforms

我必须使用一个是Form1.cs,一个是Form2.cs

在form1.cs中我有一个tabControl1,我想在我点击FORM2.cs中的按钮时向tabcontrol1(form1)添加一个标签页

这是可能的

4 个答案:

答案 0 :(得分:0)

tabControl1公开为form1的公共财产。

答案 1 :(得分:0)

使用事件和代理,我的意思是在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");
    }
}

答案 2 :(得分:0)

挂钩事件的示例:

文件: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());
        }
    }
}

答案 3 :(得分:0)

当我离开Form2时,我写了一个包含任何内容的文本文件。 (仅检查存在的事实。没有读取任何内容,但我认为它的内容可用于更新Form1上的文本框。)这会将Form1返回到屏幕。 Form1中有一个计时器,间隔为5秒。计时器检查是否存在以Form2编写的文件。如果它存在,它将被删除,并且(文件的)删除后的代码使用任何必要的程序更新Form1。

相关问题