如果已进行更改,如何在退出时显示消息框?

时间:2013-11-04 15:55:05

标签: c# .net winforms

如果用户更改了图片框中的图像,例如使用旋转R,旋转L按钮,然后用户点击退出按钮,我希望它显示一个消息框,说“你想要吗?保存对以下项目的更改?“我似乎无法做到这一点,这就是我所拥有的一切。

3 个答案:

答案 0 :(得分:2)

您需要设置一个标志以确定是否单击了该按钮。然后在Exit_Click

中检查该标志
private void Exit_Click(object sender, EventArgs e)
{
    if (_rotrButtonClicked &&
        MessageBox.Show("Would you like to save this file?",
            "Media Player",
            MessageBoxButtons.YesNo) == DialogResult.Yes)
    {
        // save the changes
    }
}

您可以在表单上将该标记声明为private字段:

private bool _rotrButtonClicked;

然后在RotRButton_Click设置它:

_rotrButtonClicked = true;

答案 1 :(得分:1)

您应该将逻辑封装到可以跟踪更改状态的类中。 E.G。

public class ImageMutator
{
    private bool HasChanged { get; set; }   
    private PictureBox myPictureBox {get;set}
    public ImageMutator(PictureBox pictureBox)//Most abstract type that has functionality
    {
       myPictureBox = pictureBox;
    }
    public void RotateRight()
    {
        HasChanged = true;
        //manipulate myPictureBox
    }

    public void RotateLeft()
    {
        HasChanged = true;
        //manipulate myPictureBox
    }

    //other methods

    public void ConfirmChange()
    {
        if (HasChanged)
        {
            var save = (MessageBox.Show("Would you like to save this file?", "Media Player", MessageBoxButtons.YesNo) == DialogResult.Yes);
            if (save)
            {
                //Save
            }

        }
    }
}

然后,您可以将此类添加为表单的成员,并在退出时确认:

public partial class Form1 : Form
{
    private ImageMutator mutator ;/private member "has-a" relationship

    public Form1()
    {
        InitializeComponent();
        mutator = new ImageMutator(pictureBox);//whatever image type is
    }

    private void Exit_Click(object sender, EventArgs e)
    {
        mutator.ConfirmChange();//Only saves if mutation occurred         
    }
}

答案 2 :(得分:0)

当用户点击“旋转”按钮时,您必须跟踪更改。在退出按钮中,您只需检查变量的值,以了解是否有变化:

private bool hasChanges = false;

private void RotRButton_Click(object sender, EventArgs e) {
    hasChanges = true;
}

private void Exit_Click(object sender, EventArgs e)
{
    if (hasChanges)
    {
        if (MessageBox("Would you like to save this file?", "Media Player", MessageBoxButtons.YesNo) == DialogResult.Yes) {
           //Do something
        }

    }
}