I am creating a Windows universal app and I would like to implement some behavior for the (hardware)back button. I am able to do so for windows Phone using
'using Windows.Phone.UI.Input;'
and
'HardwareButtons.BackPressed += HardwareButtons_BackPressed;'
But can't seem to do it with the universal app, This behavior will happen on a page that is shared. How can I do this?
You can use SystemNavigationManager
SystemNavigationManager currentView = SystemNavigationManager.GetForCurrentView();
And have an event handler like this one:
currentView.BackRequested += CurrentView_BackRequested;
private void CurrentView_BackRequested(object sender,BackRequestedEventArgs e) {
e.Handled = true;
if(Frame.CanGoBack)
try { Frame.GoBack(); }
catch(Exception) { }
}
And to Visible Back Button at corner of ur app (Desktop mode) :
currentView.AppViewBackButtonVisibility = AppViewBackButtonVisibility.Visible;
Related
I am developing a UWP application for Windows 10. I want to show a message dialog box when user reduces the size of the window. As of now, I have tried to implement the feature using this link. My purpose is being fulfilled here except the message dialog appears when user either minimizes the window or changes its size. I have also attached the code snippet below. Thank you.
private async void CoreWindow_SizeChanged(Windows.UI.Core.CoreWindow sender, Windows.UI.Core.WindowSizeChangedEventArgs args)
{
var appView = ApplicationView.GetForCurrentView();
MessageDialog messageDialog = new MessageDialog("");
if (!appView.IsFullScreen)
{
if (!msgboxshown)
{
messageDialog = new MessageDialog("To run the application smoothly, please maximize the window.");
msgboxshown = true;
await messageDialog.ShowAsync();
msgboxshown = false;
}
}
args.Handled = true;
}
My purpose is being fulfilled here except the message dialog appears when user either minimizes the window or changes its size.
When app minimizes, it will invoke EnteredBackground event, you could detect it and show your message dialog.
public App()
{
this.InitializeComponent();
this.Suspending += OnSuspending;
this.EnteredBackground += App_EnteredBackground;
}
private async void App_EnteredBackground(object sender, EnteredBackgroundEventArgs e)
{
var messageDialog = new MessageDialog("To run the application smoothly, please maximize the window.");
await messageDialog.ShowAsync();
}
Update
As #Raymond Chen said, it looks os bug. So please use the above methods with caution.
I've got a problem with the Windows.UI.Popups.MessageDialog class. The thing is: I want to ask the user if (s) he wants to close the app, when clicking the back button (on the first Page). I've tried two approaches:
First is setting the BackPressed method async:
private async void HardwareButtons_BackPressed(object sender, Windows.Phone.UI.Input.BackPressedEventArgs e)
{
Windows.UI.Popups.MessageDialog logout = new Windows.UI.Popups.MessageDialog("Do You want to close the app?");
logout.Commands.Add(new Windows.UI.Popups.UICommand("Yes", Exit));
logout.Commands.Add(new Windows.UI.Popups.UICommand("No"));
await logout.ShowAsync();
}
Second is using the System.Threading.Tasks.Task.WaitAny(...) method:
private void HardwareButtons_BackPressed(object sender, Windows.Phone.UI.Input.BackPressedEventArgs e)
{
Windows.UI.Popups.MessageDialog logout = new Windows.UI.Popups.MessageDialog("Do You want to close the app?");
logout.Commands.Add(new Windows.UI.Popups.UICommand("Yes", Exit));
logout.Commands.Add(new Windows.UI.Popups.UICommand("No"));
System.Threading.Tasks.Task.WaitAny(logout.ShowAsync().AsTask());
}
What I get is:
First: the MessageDialog shows just for a sec, then app minimizes, switching to it, and pressing the back button, just minimizes app again, but MessageDialog is not shown).
Second: it's a deadlock (after clicking "Yes", MessageDialog closes, but the Exit() method is not called, app freezes).
First of all:
Microsoft recommends that apps not close themselves programmatically.
See here:
App lifecycle - Windows app development
That page says:
You can't include any UI in your app to enable the user to close your app, or it won't pass the Store certification process.
Although I know that there are apps in the Store that do this anyway.
Anyway, in the HardwareButtons_BackPressed event handler, e.Handled = true; is needed to prevent the app from closing. This also applies for when navigating backwards in your app.
Besides this, Frame.CanGoBack should be checked to see if the app should navigate or close.
Also, you should not need to use a task, but just await MessageDialog.ShowAsync(), although you could create a task that returns a boolean telling whether to proceed or not.
Here is an entire code example to use that handles navigating backwards in the frame stack and displays a message dialog asking whether to close the app or not when the first frame is reached:
App.xaml.cs:
using Windows.Phone.UI.Input;
using Windows.UI.Popups;
public sealed partial class App : Application
{
public App()
{
HardwareButtons.BackPressed += HardwareButtons_BackPressed;
}
private async void HardwareButtons_BackPressed(object sender, BackPressedEventArgs e)
{
Frame frame = Window.Current.Content as Frame;
if (frame == null) { return; }
e.Handled = true;
if (frame.CanGoBack) { frame.GoBack(); return; }
else
{
string content = "Do you want to close the app?";
string title = "Close Confirmation";
MessageDialog confirmDialog = new MessageDialog(content, title);
confirmDialog.Commands.Add(new UICommand("Yes"));
confirmDialog.Commands.Add(new UICommand("No"));
var confirmResult = await confirmDialog.ShowAsync();
// "No" button pressed: Keep the app open.
if (confirmResult != null && confirmResult.Label == "No") { return; }
// "Back" or "Yes" button pressed: Close the app.
if (confirmResult == null || confirmResult.Label == "Yes") { Current.Exit(); }
}
}
}
In my UWP app when i click on mobile back button app get close, so add this code in app.xaml.cs
private async void HardwareButtons_BackPressed(object sender, BackPressedEventArgs e)
{
e.Handled = true;
Frame rootFrame = Window.Current.Content as Frame;
if (rootFrame.CanGoBack && rootFrame != null)
{
rootFrame.GoBack();
}
else
{
var msg = new MessageDialog("Confirm Close! \nOr Press Refresh Button to Go Back");
var okBtn = new UICommand("OK");
var cancelBtn = new UICommand("Cancel");
msg.Commands.Add(okBtn);
msg.Commands.Add(cancelBtn);
IUICommand result = await msg.ShowAsync();
if (result != null && result.Label == "OK")
{
Application.Current.Exit();
}
}
}
and
public App()
{
this.InitializeComponent();
this.Suspending += OnSuspending;
/* Because of this line my app work on mobile great but when
when i debug on pc it through exception "show in image" */
HardwareButtons.BackPressed += HardwareButtons_BackPressed;
}
After Done all this code when i debug app on phone, app successfully run -
Mobile Debuging:
But when debug in pc with same code, it show this error- PC Debuging:
when i remove HardwareButtons.BackPressed += HardwareButtons_BackPressed; then issue with pc debugging resolved but in mobile debuging back button again is not work.
The reason is that HardwareButtons API is not the universal solution for handling the back button. This API is available only in the Mobile extension SDK and trying to invoke it on other SKU will cause this exception, because the type is not available.
To enable the same functionality on all systems, you will need to use the new universal back button event:
SystemNavigationManager.GetForCurrentView().BackRequested += BackButtonHandler;
This will work the same on phone, PC, tablets,Xbox One, Surface Hub and HoloLens.
On PC this button is not shown by default, so you have to display it manually or create your own. To show the Back button in window's title bar, use:
SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility =
AppViewBackButtonVisibility.Visible;
It is recommended that you hide this button once Frame.CanGoBack is false, because in that case the button is no longer useful. You should do this after each navigation of the frame. Best place to do this is when setting up the root frame in App.xaml.cs:
Frame rootFrame = Window.Current.Content as Frame;
rootFrame.Navigated += UpdateAppViewBackButton;
Now the handler could look like this:
private void UpdateAppViewBackButton( object sender, NavigationEventArgs e )
{
Frame frame = (Frame) sender;
var systemNavigationManager = SystemNavigationManager.GetForCurrentView();
systemNavigationManager.AppViewBackButtonVisibility =
frame.CanGoBack ? AppViewBackButtonVisibility.Visible :
AppViewBackButtonVisibility.Collapsed;
}
On Application close
I have also noticed that you are using Application.Current.Exit(); to exit the app. This is however not recommended. Once the user chooses OK in the dialog, you should rather set the e.Handled = false and let the system handle the app close manually. This will ensure the app suspension will run as expected and the app will stay in memory if the system has enough resources and will then launch faster again. Application.Current.Exit() kills the application and it is not recommended for UWP apps.
One thing to remember is that on Desktop, there is currently no way to catch the user clicking the close button in the app's title bar, so your confirmation dialog will not display in that case unfortunately.
I am currently developing a windows 8 metro app in that I want to pause my app (Basically game) when charms bar opens up that I am doing :
CustomSettingFlyout.Show();
PauseGame();
But after user closes the Charm bar I want to resume my game.I thought there would be an event that says that the charms has been closed, but that's not the case. What's the correct way of to get charms bar got closed?
I also tried this :-
Window.Current.Activated += Current_Activated;
Added this in main class's Constructor
void Current_Activated(object sender, WindowActivatedEventArgs e)
{
if (e.WindowActivationState == CoreWindowActivationState.CodeActivated)
{
if (CharmsActivated)
{
CharmBar.IsOpen = true;
CharmsActivated = false;
ResumeGame();
}
}
if (e.WindowActivationState == CoreWindowActivationState.Deactivated)
{
if (CharmBar.IsOpen == true)
{
CharmsActivated = true;
CharmBar.IsOpen = false;
PauseGame();
}
}
}
But that is not working.Please tell me if there is another way to do this.
(C#, XAML, Windows 8.1 app)
I have created setup of my application using Windows Installer.
Now I want to Start application at Windows Start-Up and move it system minimize tray as i don't want to display GUI(View) at Windows Start-Up.
I have searched in Google and i found to use Registry key But that is not enough for me as i also want to move to system minimize tray and application run.
My purpose to do it is, user do not feels annoying when application starts every time when he/she starts system.
Can anyone have answer?
Thanks..
In your application, add an event handler for the FrameworkElement.Loaded event. In that handler, add the following code:
WindowState = WindowState.Minimized;
This will minimise the application when it starts.
To start the application when the computer starts, you'll need to add your program into Windows Scheduler and set it to run at startup. You can find out more on the Schedule a task page at MSDN.
You also have to set this property to remove it from the taskbar
ShowInTaskbar= false;
Maybe this answer is late, but I still want to write it down to help those who haven't found solutions yet.
Firstly you need to add a function to minimize your app to tray when it autostarts as system startup.
In your App.xaml file, change the original StartupUri=... to Startup="App_Startup" as below. App_Startup is your function name and can be changed.
<Application x:Class="Yours.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Startup="App_Startup">
In your App.xaml.cs file. Add the function below:
public partial class App : Application
{
private void App_Startup(object sender, StartupEventArgs e)
{
// Process command line args
var isAutoStart = false;
for (int i = 0; i != e.Args.Length; ++i)
{
if (e.Args[i] == "/AutoStart")
{
isAutoStart = true;
}
}
// Create main application window, starting minimized if specified
MainWindow mainWindow = new MainWindow();
if (isAutoStart)
{
mainWindow.WindowState = WindowState.Minimized;
}
mainWindow.OnAutoStart();
}
}
In your MainWindow.xaml.cs, add a function as below:
public void OnAutoStart()
{
if (WindowState == WindowState.Minimized)
{
//Must have this line to prevent the window start locatioon not being in center.
WindowState = WindowState.Normal;
Hide();
//Show your tray icon code below
}
else
{
Show();
}
}
Then you should set you app utostart as system start.
Now if you have a switch to decide whether you app to autostart as system start, you can just add the function below as your switch status changed event function.
private void SwitchAutoStart_OnToggled(object sender, RoutedEventArgs e)
{
const string path = #"SOFTWARE\Microsoft\Windows\CurrentVersion\Run";
var key = Registry.CurrentUser.OpenSubKey(path, true);
if (key == null) return;
if (SwitchAutoStart.IsOn)
{
key.SetValue("Your app name", System.Reflection.Assembly.GetExecutingAssembly().Location + " /AutoStart");
}
else
{
key.DeleteValue("Your app name", false);
}
}
If you want to automatically start the application for all users on Windows startup, just replace the forth line with
RegistryKey key = Registry.LocalMachine.OpenSubKey(path, true);
^_^