在c#中发生来自另一个类的事件后执行代码的最佳方法

时间:2014-12-25 20:58:53

标签: c# .net winforms

我们说form A有一个按钮'运行向导'。单击此按钮可打开向导以创建内容。此向导从另一个项目导入,该项目形成A引用。该向导在其工作期间创建了几个数组。

这是点击按钮的代码:

private void buttonOpenWizard_Click(object sender, EventArgs e)
        {
            SampleWizard wizard = new SampleWizard();
            wizard.Show();
            //(theoretical code using arrays created by the wizard)
        }

等待向导完成并在完成向导任务后运行理论代码的最佳方法是什么?

2 个答案:

答案 0 :(得分:2)

由于您似乎不介意阻止,请使用ShowDialog

private void buttonOpenWizard_Click( object sender, EventArgs e )
{
    SampleWizard wizard = new SampleWizard();
    if( wizard.ShowDialog() == DialogResult.OK ) // this line will block until the wizard form is closed
    {
        // and any code here will not run until that has happened
    }
}

通常使用ShowDialog调用的返回值来指示用户是否完成了向导/对话框。在这种情况下,我无法知道该表单是否使用了该表单,但在此我已经假设它已经使用了。

如果您不想阻止,您应该能够做到这样的事情:

private void buttonOpenWizard_Click( object sender, EventArgs e )
{
    SampleWizard wizard = new SampleWizard();
    wizard.FormClosed += WizardClosed; // hook up event handler
    wizard.Show();
}

private void WizardClosed( object sender, FormClosedEventArgs e )
{
    var wizard = (SampleWizard)sender;
    // check and use result of wizard here
}

答案 1 :(得分:1)

private void buttonOpenWizard_Click(object sender, EventArgs e)
    {
        SampleWizard wizard = new SampleWizard();
        if(wizard.ShowDialog()== DialogResult.OK) //Set the dialog result to ok in your form, if it would closed corret
        {
         //(theoretical code using arrays created by the wizard)
        }

    }