在C#的消息框中单击X时的书写代码

问题描述 投票:1回答:1

我在Visual Studio 2017中用C#编写应用程序。我正在使用Windows Forms App(.NET Framework)。我弹出了一个MessageBox及其默认设置(只有OK按钮和右上角的X)。当用户选择“确定”时,其余代码将恢复。我想编写单独的代码,以在用户选择X关闭消息框时运行。如何判断用户是否单击了X以关闭消息框?

我尝试使用

DialogResult result = MessageBox.Show("Message here");
if(result != DialogResult.OK){
    //Do stuff here
} 

但是即使按下X,结果仍然会以Dialog.OK的形式返回。

我该怎么办?

c# messagebox dialogresult
1个回答
0
投票

尝试一下:

DialogResult result = MessageBox.Show("Message here", "", MessageBoxButtons.OK, MessageBoxIcon.None, MessageBoxDefaultButton.Button2);
if (result != DialogResult.OK) {
    //Do stuff here
}

它将默认按钮定义为不存在的按钮,因此结果应不等于DialogResult.OK。

© www.soinside.com 2019 - 2024. All rights reserved.