永远不会调用Winform的OK按钮

时间:2014-01-22 20:40:50

标签: c# winforms

我正在开发一个Grasshopper组件,这是一个Rhino 3D插件,可以进行图形化编程。我有一个来自winforms的代码片段,如下所示:

    public void ShowForm()
    {
        hmf.ShowDialog();

        if (hmf.ShowDialog() == DialogResult.OK) {

            MessageBox.Show("DialogResultOK was hit.");
            // store winforms values into global vars

            try
            {
                MessageBox.Show(Params.Input[0].ToString());
                Grasshopper.Kernel.Parameters.Param_String param = (Grasshopper.Kernel.Parameters.Param_String)Params.Input[0];
                param.PersistentData.Clear();
                for (int i = 0; i <= x.Count - 1; i++)
                {
                    param.PersistentData.Append(new GH_String(x[i]));
                }
                param.ExpireSolution(true);
            }
            catch (Exception ex)
            {
                // error message
            }
        }
        else if (hmf.ShowDialog() == DialogResult.Cancel)
        {
            MessageBox.Show("DialogResultCancel was hit.");
            this.ExpireSolution(false);
        }
    }

它提供了两个条件:DialogResult.OKDialogResult.Cancel。理论上,当调用OK时,它会将winforms值保存到我的全局变量中,否则它会转到DialogResult.Cancel

出于某种原因,当我使用MessageBox.Show("...")时,它表明永远不会调用OK

以下是forms代码:

    private void button1_Click(object sender, EventArgs e) // ok
    {
    }

    public Button button1Object{ get { return this.button1; } }

    private void button2_Click(object sender, EventArgs e) // cancel
    {

    }

    public Button button2Object { get { return this.button2; } }

这就是我form的样子。

enter image description here

1 个答案:

答案 0 :(得分:4)

您正在调用ShowDialog()函数三次!调用一次并将其结果放入变量中。每次调用它时,都会有不同的响应。您的方法使您的“if”语句具有无法访问的代码块。

public void ShowForm()
{
    var a = hmf.ShowDialog();

    if (a == DialogResult.OK) {

        MessageBox.Show("DialogResultOK was hit.");
        // store winforms values into global vars

        try
        {
            MessageBox.Show(Params.Input[0].ToString());
            Grasshopper.Kernel.Parameters.Param_String param = (Grasshopper.Kernel.Parameters.Param_String)Params.Input[0];
            param.PersistentData.Clear();
            for (int i = 0; i <= x.Count - 1; i++)
            {
                param.PersistentData.Append(new GH_String(x[i]));
            }
            param.ExpireSolution(true);
        }
        catch (Exception ex)
        {
            // error message
        }
    }
    else if (a == DialogResult.Cancel)
    {
        MessageBox.Show("DialogResultCancel was hit.");
        this.ExpireSolution(false);
    }
}