blink
blink

Reputation: 163

xna c# trap and cancel the close window (x) button and Ctrl F4

(xna c#) i would like to be able to trap any close window event in my game so i can generate an "are you sure?" message so the user can prevent the game from terminating. how do i trap the appropriate event and how do i prevent the game from ending? this is for windows only. i have tried a number of methods already including EndRun() but they all seem to be too late to do anything about ending the game. ie the window is already closed and there is no way to about the exit.

Upvotes: 2

Views: 1238

Answers (2)

blink
blink

Reputation: 163

thank you very much for your help. i am only answering here because i dont now how to add code in the comments. i solved the problem as follows;

this code gets the Form and allows me to set a closing event;

Form MyGameForm = (Form)Form.FromHandle(Window.Handle);
MyGameForm.Closing += ClosingFunction;

my ClosingFunction looks like this;

public void ClosingFunction (object sender, System.ComponentModel.CancelEventArgs e)
{

    if (MyMsgBox.Show("Are you sure you want to exit withou saving?", "Exit") == false)
    {
        e.Cancel = true; // Cancel the closing event
        return;
    }
}

In order to use this code you need to add a .NET Systems.Windows.Forms reference to you project

Upvotes: 4

Blue0500
Blue0500

Reputation: 725

In C#, you can override WndProc to catch the Windows messages before they reach your application. Here, I overrode the WM_CLOSE message to display a messagebox before closing the form.

protected override void WndProc(ref Message m) {
    if (m.Msg == 0x10) {
        if (MessageBox.Show("Do you really want to exit?", "Exit Game", MessageBoxButtons.YesNo) == DialogResult.No)
            return;
    }
    base.WndProc(ref m);
}

This doesn't close the window until the user confirms that he wants to. Hope this helps!

Upvotes: 1

Related Questions