I'm writing a windows phone app, and I want to know how to alert and make sure the that user really wants to exit the app on the back key press. Pretty simple.
Thanks.
I assume your navigation is set up such that the user can only exit from the first page. If so, in that page, you can override the OnBackKeyPress event and cancel the button press. I haven't tested this code, but seems like it should work:
protected override void OnBackKeyPress(CancelEventArgs e)
{
if(MessageBox.Show("Are you sure you want to exit?","Exit?",
MessageBoxButton.OKCancel) != MessageBoxResult.OK)
{
e.Cancel = true;
}
}
Edit - I'll leave this here as an example of overriding the back button, but the correct answer in this context is to not implement the feature.
While the previous answer about cancelling OnBackKeyPress may technically work, it could cause your app to fail certification requirements. See the following link:
http://msdn.microsoft.com/en-us/library/hh184840(v=VS.92).aspx
5.2.4.2 – Back Button: First Screen
Pressing the Back button from the first screen of an application must close the application.
I would recommend not implementing this functionality.
Related
I am developing a windows phone 8 app. I want to control the back button of the phone for doing specific task. I want that when user press the back button in specific page it will not navigate to the previous page but to the page which I want. Is their any way to control the hardware back button present in phone?
In Silverlight apps (WP7, WP8, WP8.1) you do this:
protected override void OnBackKeyPress(CancelEventArgs e)
{
// put any code you like here
MessageBox.Show("You pressed the Back button");
e.Cancel = true;
}
That will work in all Windows Phone versions if you're using Silverlight.
If you're using WinRT for Windows Phone 8.1, it is a bit different:
Open NavigationHelper.cs and make this modification:
private void HardwareButtons_BackPressed(object sender, Windows.Phone.UI.Input.BackPressedEventArgs e)
{
if (this.GoBackCommand.CanExecute(null) && !e.Handled)
{
e.Handled = true;
this.GoBackCommand.Execute(null);
}
}
Now in your app page (the page that will be open when the back button is pressed), add the following namespace:
using Windows.Phone.UI.Input;
Add this handler to the constructor method of your page:
HardwareButtons.BackPressed += OnBackPressed;
Then add this method:
private async void OnBackPressed(object sender, Windows.Phone.UI.Input.BackPressedEventArgs e)
{
e.Handled = true;
// add your own code here to run when Back is pressed
}
Note: in both cases, the 'e.Handled = true' line tells the OS that the back button press has been handled, and therefore the OS will not action the default behaviour. If you remove that line your own code will run, and the OS will also do its own backwards navigation.
Be mindful of Rowland's comment about overriding the Back button - if you're not navigating intuitively you will confuse the user and risk your game being rejected (if you just need to control a pause screen or menu it will be fine, but if you implement something gimmicky like using the Back button as a game control you'll be in trouble).
My blog has the same answer with a bit more detail if you need it:
http://grogansoft.com/blog/?p=572
Whilst it possible to cancel the navigation event, and permissable in a game to present a pause screen or similar, generally it is not allowed to use the back button for anything other than backward navigation in an app; Per requirement 5.2.4 of the Technical certification requirements for Windows Phone
To maintain a consistent user experience, the Back button must only be used for backwards navigation in the app.
If you are creating a XAML app where it is permissible to cancel a "back" operation, such as per 5.2.4.4 of the Technical certification requirements for Windows Phone
:
For games, when the Back button is pressed during gameplay, the game can choose to present a pause context menu or dialog, or it can navigate the user to the prior menu screen.
Then you can implement this by overriding the OnNavigatingFrom method on your page, and set the Cancel property of the NavigatingCancelEventArgs, so something like this example from Frame, page, and navigation features for Windows Phone 8:
protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
{
base.OnNavigatingFrom(e);
// If the navigation can be cancelled, ask the user if they want to cancel
if (e.IsCancelable)
{
MessageBoxResult result = MessageBox.Show("Do you want to stay here?", "Confirm Navigation from Page", MessageBoxButton.OKCancel);
if (result == MessageBoxResult.OK)
{
// User wants to stay here
e.Cancel = true;
return;
}
}
}
Of course, you may choose to implement the prompt differently, but that should illustrate how it is possible.
I've got TextBoxes in a C# form. The user enters data, and then when they leave the control (almost always by hitting Tab), I check the data to make sure it's valid. If it is invalid, I want to highlight their text so they can immediately fix it rather than having to click it.
Right now, on Control.Leave, I validate their entry. This works just fine. However, since they hit Tab, right after they dismiss the error message, it goes on to the next object, even though I've got ((TextBox)sender).Focus();
How can I have the above line fire after the form Tabs to the next control.
You may want to look into Control.CausesValidation property
http://msdn.microsoft.com/en-us/library/system.windows.forms.control.causesvalidation(v=vs.110).aspx
You can validate the control prior to the user leaving focus rather than waiting on Focus moving itself.
And here's MSDN documentation for Control.Validating event, does a good job at laying out the sequence of events when gaining / losing focus of a Control.
http://msdn.microsoft.com/en-us/library/system.windows.forms.control.validating(v=vs.110).aspx
Notice how Control.Validating and Control.Validated are launched prior to Control.LostFocus. You can perform your validation step prior to allowing the user to lose focus of your Textbox.
There's also a pretty good previous answer on stackoverflow.com which outlines how to do this: C# Validating input for textbox on winforms
If you handle the Control.Validating event, setting e.Cancel to true will stop the change of focus from occurring.
Note that this method will also stop buttons from working, so you may need to set Control.CausesValidation to false on certain buttons.
You will also need the following snippet on the main form to allow the close button to work:
protected override void OnFormClosing(FormClosingEventArgs e) {
e.Cancel = false;
base.OnFormClosing(e);
}
Try using the LostFocus event on the TextBox to Focus it again
I have this weird problem.
I made an app which has to react to the keyboard keys (1,2,3,4,...), but it doesn't.
Well, actually it does but only if I click a button and hold it clicked, if I let it go the keys, again, stop to react.
The method I used is KeyDown, it is placed in Page
KeyDown="Page_KeyDown" in XAML
and in Code:
private void Page_KeyDown(object sender, KeyRoutedEventArgs e)
{
switch (e.Key)
{
case Windows.System.VirtualKey.Number1:
{
KeyDownHelper(1);
break;
}
}
...
}
It has many cases but all of them are pretty the same, and I guess that the problem isn't inside the method but with my thinking.
I think the problem is that the page kind of loses focus maybe? But not sure if that is the case and how to deal with it
It sounds like you want your app to listen for individual key presses, rather just when they key is held down, is that right? In that case you should respond to the Key Up event. That way you will be able to react to each individual key press, and ignore times when the key is held down.
Here is a link to an MSDN article on Key Up: Key Up MSDN Article
Does that help?
I think you are looking for the CoreDispatcher.AcceleratorKeyActivated API.
For your reference CoreDispatcher.AcceleratorKeyActivated
I'm trying to tighten navigation in my WP8 app and I'm having an issue where I want to exit when the user is on the main xaml page (which could be navigated to from many pages within my app). The simplest way about it seemed to let the back button handle exiting, but in order to do this it seems you need to clear the back button's history so that it can exit.
MSDN says to use the NavigationService.RemoveBackEntry method to clear out back entries (and thus allowing the app to close naturally once the user clicks Back again). But I'm not seeing this method! What gives?
http://msdn.microsoft.com/en-us/library/windowsphone/develop/system.windows.navigation.navigationservice.removebackentry(v=vs.105).aspx
yes your point is correct. you can clear the back entry and exit by the following piece of code.
protected override void OnNavigatedTo(NavigationEventArgs e)
{
while (NavigationService.CanGoBack)
{
NavigationService.RemoveBackEntry();
}
}
you can use this to terminate the app in Windows Phone 8 (Just remember to save all your program data before calling this ;-))
App.Current.Terminate();
I have a strange issue overriding BackkeyPress Function in code behind, inside the function i have a simple message box to Go back or cancel navigation ( stay in current page ), when no choice is made (ok or cancel ) and Messagebox is open for long time, Application crashes, when i try to debug, no exception is thrown and App remains in the state unless OK or cancel is pressed , but on Normal run ( without debugger ) the crash is apparent.
protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
{
string caption = "exit?";
string message = "Do you still want to exit?";
e.Cancel = MessageBoxResult.Cancel == MessageBox.Show(message, caption,
MessageBoxButton.OKCancel);
base.OnBackKeyPress(e);
}
http://msdn.microsoft.com/en-US/library/windowsphone/develop/jj206947(v=vs.105).aspx
In Windows Phone 8, if you call Show in
OnBackKeyPress(CancelEventArgs) or a handler for the BackKeyPress
event, the app will exit.
You can work around this by calling Show on a different thread, as
described in the following steps. Override BackKeyPress or create a
handler for the BackKeyPress event. Set the Cancel to true to cancel
the back key press action. Dispatch a method that shows the
MessageBox. If the user chooses to leave the app, call Terminate(),
otherwise, do nothing.
I found one more solution to this, so I thought it would be good if I posted it here. It's just a workaround though.
private async void PhoneApplicationPage_BackKeyPress (object sender, System.ComponentModel.CancelEventArgs e)
{
e.Cancel = true;
await Task.Delay(100);
if (MessageBox.Show(msg, cap, MessageBoxButton.OKCancel) == MssageBoxResult.OK)
{
//somecode
}
}
Source
When using Terminate() - be aware that a number of app.xaml.cs rootFrame navigating events associated with normal exit won't trigger, neither the ApplicationClosing or your page's OnNavigatedFrom. So check if anything going on is important. You might tack it on before terminating...