I need to ovveride the windows back button when i am clicking from my application .I tried 2 method below but it is not working in windows phone 8 ?
methods 1)
protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
{
e.Cancel = true;
var result = MessageBox.Show("Do you want to exit?", "Attention!",
MessageBoxButton.OKCancel);
if (result == MessageBoxResult.OK)
{
// base.OnBackKeyPress(e);
return;
}
e.Cancel = true;
}
method 2 )
a) wrote this in xaml heading
BackKeyPress="MyBackKeyPress"
b) Initlize this in constructor
BackKeyPress += OnBackKeyPress;
c) and call this method
private void MyBackKeyPress(object sender, System.ComponentModel.CancelEventArgs e)
{
e.Cancel = true; //tell system you have handled it
//you c
}
the two of the methods are not working . when i was clicked the back button the app destroyed and unable to get the control of backbutton . Any help ?
As per certification requirements it is not recommended to override the back button -
Pressing the Back button from the first screen of an app must close
the app.
http://msdn.microsoft.com/en-us/library/windowsphone/develop/hh184840%28v=vs.105%29.aspx
You can try this code
protected override void OnBackKeyPress(CancelEventArgs e)
{
if(MessageBox.Show("Are you sure you want to exit?","Confirm Exit?",
MessageBoxButton.OKCancel) != MessageBoxResult.OK)
{
e.Cancel = true;
}
}
Try this one, which works for me
Step 1 : in XAML
BackKeyPress="PhoneApplicationPage_BackKeyPress"
Step 2 : in C#
private void PhoneApplicationPage_BackKeyPress(object sender, System.ComponentModel.CancelEventArgs e)
{
MessageBoxResult mRes = MessageBox.Show("Would you like to exit?", "Exit", MessageBoxButton.OKCancel);
if (mRes == MessageBoxResult.OK)
{
NavigationService.GoBack();
}
if (mRes == MessageBoxResult.Cancel)
{
e.Cancel = true;
}
}
In your MyBackKeyPress
method, throw a new exception to close the app in the runtime and return to the phone's menu. I don't know if this is a good way to achieve it, but this definitely solves the problem.
private void MyBackKeyPress(object sender, System.ComponentModel.CancelEventArgs e)
{
throw new Exception();
}
Test this on emulator/device without Dubugging
in Visual Studio
and you will see that your app closes.
I tried the same . but it is not working . i put the breakpoints inside the code and also found its not entering or not calling the function when i click back button . – user1703145 45 mins ago
You haven't forgotten to bind this event in XAML?
<phone:PhoneApplicationPage ..... BackKeyPress="phoneApplicationPage_BackKeyPress">