如果在Form1上按下按钮,如何在Form2上运行另一段代码?

时间:2013-04-19 18:20:34

标签: c#

很难提供代码来显示正在尝试完成的内容,但这里是向下运行的:

我在Form1上有一个按钮,显示“Lock On”,我在Form2中有一个语句,在按下“lock on”之前从Form1读取数据(如加载所有表单时)。我希望Form1读取数据IF按下“锁定”,而不是在它之前。

有办法吗?

如果按下这就是我要运行的内容:

private void FOne_Reader_Tick(object sender, EventArgs e)
    {
        //Reads fruit information

        //if lock on is pressed, do this:
        FOne_Reader.Enabled = true;
        Fruit fruity = new Fruit();
        string FileToRead = "../../../DLL/XML/Fruit_Event.xml";
        XmlSerializer serializer = new XmlSerializer(typeof(Fruit));
        fruity = (Fruit)XMLHandler.READXML(FileToRead, serializer);

        //if not
      ...

1 个答案:

答案 0 :(得分:0)

使用事件尝试:

Form1代码:

public partial class Form1 : Form
{
    public event Action PressLock;
    public Form1()
    {
        InitializeComponent();
    }

    protected override void OnLoad(EventArgs e)
    {
        base.OnLoad(e);

        Form2 dlg=new Form2();
        dlg.OtherFrom=this;            
        dlg.Show();
    }

    private void lockOnButton_Click(object sender, EventArgs e)
    {
        if(this.PressLock!=null)
        {
            this.PressLock();
        }
    }
}

Form2代码:

public partial class Form2 : Form
{
    public Form2()
    {
        InitializeComponent();
    }
    Form1 form;
    public Form1 OtherFrom
    {
        get { return form; }
        set
        {
            this.form=value;
            this.form.PressLock += new Action(ReadFromForm1);
        }
    }

    public void ReadFromForm1()
    {
        // xml reading here
    }
}