簡體   English   中英

單擊“消息框”按鈕之后,但此消息框關閉之前該怎么辦?

[英]How to do something after clicking on MessageBox button, but before this MessageBox closes?

我在每個項目的文本框中都有一些“項目”列表和一些信息。 用戶可以選擇一個項目,然后修改信息,然后單擊保存按鈕。

如果我更改選定的項目而不保存所做的修改,則會出現“是/否”消息框:

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

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

在單擊“是/否”按鈕后,我將刷新所有項目列表(使用我自己的Refresh()方法),但會停留在MessageBox上直到刷新完成。

可能嗎?

內置的MessageBox類不允許這種復雜的行為。

一種方法是創建自己的消息框。 創建Form的子類,添加一些標簽和按鈕。 公開一些事件,例如YesClickedNoClicked

在主窗體中,創建自定義消息框的實例,訂閱事件,然后在其上調用ShowDialog

刷新完成后,可以在自定義消息框上調用“ Close或“ Dispose ”以將其關閉。

嘗試創建一個自定義消息框。 我對代碼進行了注釋,如果需要澄清,請告訴我

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

您可以使用DialogResult根據單擊的按鈕更改發生的情況

DialogResult dialogResult = MessageBox.Show(@"Some body", @"Title", MessageBoxButtons.YesNo);
if (dialogResult == DialogResult.Yes)
{
   // do stuff
}

不,一個消息框不能執行此操作。 這不是要這樣做。 它只是在框中顯示一條消息...)

您始終可以做的是創建自己的窗口,該窗口看起來像一個消息框,其行為類似於一個消息框,但是當您單擊按鈕時實際上會執行操作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM