单击“消息框”按钮之后,但此消息框关闭之前该怎么办?

时间:2019-02-08 14:55:12

标签: c# .net winforms

我在文本框中为每个项目提供了“项目”列表和一些信息。用户可以选择一个项目,然后修改信息,然后单击保存按钮。

如果我更改所选项目而不保存所做的修改,则会显示“是/否”消息框:

DialogResult dialogResult = MessageBox.Show(
            "Do you want to save changes ?",
            "Title",
            MessageBoxButtons.YesNo);

if (dialogResult == DialogResult.Yes)
{
    //Click Yes
}
else
{
    //Click No
}    

在单击“是/否”按钮之后,我将刷新所有项目列表(使用我自己的Refresh()方法),但是会停留在MessageBox上直到刷新完成。

有可能吗?

4 个答案:

答案 0 :(得分:1)

内置MessageBox类不允许如此复杂的行为。

执行此操作的一种方法是创建自己的消息框。创建Form的子类,添加一些标签和按钮。公开一些事件,例如YesClickedNoClicked

在主窗体中,创建自定义消息框的实例,订阅事件,然后在其上调用ShowDialog

刷新完成后,您可以在自定义消息框中调用CloseDispose将其关闭。

答案 1 :(得分:0)

尝试创建自定义消息框。我注释了代码,让我知道是否需要澄清

public static class MessageBoxResult
{
    public static int dialogResult;  // <== i use this value to determine what button was pressed
}

// your custom message box form code
public partial class CustomMsgBox : Form
{
    public CustomMsgBox()
    {
        InitializeComponent();
    }


    public void show(string pos0, string pos1, string pos2, string message)  //<=== initializing the message box with the values from your main code
    {
        button1.Text = pos0;
        button2.Text = pos1;
        button3.Text = pos2;
        label1.Text = message;
    }


 // message box events to set the static field incase a button on the custom form was changed
    private void button1_Click(object sender, EventArgs e)
    {
        MessageBoxResult.dialogResult = 0;
        this.Close();
    }

    private void button2_Click(object sender, EventArgs e)
    {
        MessageBoxResult.dialogResult = 1;
        this.Close();
    }

    private void button3_Click(object sender, EventArgs e)
    {
        MessageBoxResult.dialogResult = 2;
        this.Close();
    }
}


//usage
{
    MessageBoxResult.dialogResult = -1;   // <== setting the static field to -1 to mean nothing was pressed
    CustomMsgBox cMsgBox = new CustomMsgBox();
    cMsgBox.show("your message");
    cMsgBox.ShowDialog();
}

答案 2 :(得分:0)

您可以使用DialogResult

根据单击的按钮来更改发生的事情
DialogResult dialogResult = MessageBox.Show(@"Some body", @"Title", MessageBoxButtons.YesNo);
if (dialogResult == DialogResult.Yes)
{
   // do stuff
}

答案 3 :(得分:-1)

否,消息框无法执行此操作。这不是要这样做。它只是在框中显示一条消息...)

您始终可以做的是创建自己的窗口,该窗口看起来像一个消息框,其行为类似于一个消息框,但是当您单击按钮时实际上会执行操作。