I want to override the backbutton on mainpage. What works on other pages does not work on main. Here's my code:
protected override void OnNavigatingFrom(System.Windows.Navigation.NavigatingCancelEventArgs e)
{
base.OnNavigatingFrom(e);
if (MessageBox.Show("Wszystkie zmiany zostanÄ… odrzucone", "Odrzucenie Zmian", MessageBoxButton.OKCancel) != MessageBoxResult.OK)
{
e.Cancel = true;
}
}
The problem is that it shows the messagebox to confirm exit, however it is also exiting the application, so confirming or cancelling makes no sense anyway.
You must override OnBackKeyPress instead of OnNavigatingFrom
protected override void OnBackKeyPress(CancelEventArgs e)
{
if (MessageBox.Show("Wszystkie zmiany zostanÄ… odrzucone", "Odrzucenie Zmian", MessageBoxButton.OKCancel) != MessageBoxResult.OK)
{
e.Cancel = true;
}
}
Related
My application appears to be skipping the Form_Closing event entirely, and I am not sure why. I have tried to debug it by using e.cancel and showing a messagebox when it closes, but the messagebox never shows, and the e.cancel doesnt cancel it. My code is
public void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (isClosed == false)
{
e.Cancel = true;
base.OnFormClosing(e);
this.Hide();
this.WindowState = FormWindowState.Minimized;
}
else
{
Application.Exit();
}
}
Thanks :)
Your method has the signature appropriate for a FormClosing event handler, but you are calling base.OnFormClosing which is only appropriate for an OnFormClosing override.
Pick one. For example, the override would look like
protected override void OnFormClosing(FormClosingEventArgs e)
{
if (isClosed == false)
{
e.Cancel = true;
base.OnFormClosing(e);
Hide();
WindowState = FormWindowState.Minimized;
}
else
{
Application.Exit();
}
}
Start by only using a message box to determine that you hace the right event
Then check the value of isclosed since I suspect it is true.
This question already has answers here:
How can I prevent a user from closing my C# application?
(4 answers)
Closed 7 years ago.
I want to close a application when a button is pressed but I wanted to disable the close button (X button upper right).
I disabled the close button with this code:
protected override void OnFormClosing(FormClosingEventArgs e)
{
e.Cancel = true;
}
But now when I try to close the program with this code it wont work.
private void button1_Click(object sender, EventArgs e)
{
Application.Exit();
}
Is there a way to close this program when the button is clicked?
In the event handler, check the CloseReason property of the FormClosingEventArgs:
This allows you to behave differently depending on how the close was initiated, so in the case of Application Exit (or Windows Shutdown) you can allow the form to close.
protected override void OnFormClosing(FormClosingEventArgs e)
{
if (e.CloseReason != CloseReason.ApplicationExitCall
&& e.CloseReason != CloseReason.WindowsShutDown)
{
e.Cancel = true;
}
}
You're cancelling ALWAYS the closign of the form, so that's why it doesn't works.
Try this:
bool blockClosing = true;
protected override void OnFormClosing(FormClosingEventArgs e)
{
e.Cancel = blockClosing;
}
private void button1_Click(object sender, EventArgs e)
{
blockClosing = false;
Application.Exit();
}
In this way, when you press your button it will allow tha pp to be closed.
FormClosingEventArgs has a Reason member that tells you what exactly is trying to close your form. Simply allow ApplicationExitCall through without canceling it.
In a Windows 10 Universal app, I want to display a MessageDialog when the back button is pressed.
The code of my page is the following :
protected override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility = AppViewBackButtonVisibility.Visible;
SystemNavigationManager.GetForCurrentView().BackRequested += GamePage_BackRequested;
}
private async void GamePage_BackRequested(object sender, BackRequestedEventArgs e)
{
var dialog = new Windows.UI.Popups.MessageDialog("Are you sure ?");
dialog.Commands.Add(new Windows.UI.Popups.UICommand("Yes"));
dialog.Commands.Add(new Windows.UI.Popups.UICommand("No"));
var result = await dialog.ShowAsync();
}
When I lauch the App in "local machine", the dialog is well displayed. But when I turn Windows to "tablet mode", or when i try it on my Windows Phone, the ShowAsync method crashes the App (with no error).
Why is the app crashing ?
The problem seems to be that the "dialog.ShowAsync()" method should be called from the UI thread.
This is how I solved it :
private void GamePage_BackRequested(object sender, BackRequestedEventArgs e)
{
e.Handled = true;
Frame rootFrame = Window.Current.Content as Frame;
if (rootFrame.CanGoBack)
{
var d = dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => ShowConfirmationDialog(rootFrame));
}
}
public async void ShowConfirmationDialog(Frame rootFrame)
{
var dialog = new Windows.UI.Popups.MessageDialog("Are you sure ?");
dialog.Commands.Add(new Windows.UI.Popups.UICommand("Yes") { Id = 0 });
dialog.Commands.Add(new Windows.UI.Popups.UICommand("No") { Id = 1 });
var result = await dialog.ShowAsync();
if (result != null && result.Label == "Yes")
{
rootFrame.GoBack();
}
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
dispatcher = Windows.UI.Core.CoreWindow.GetForCurrentThread().Dispatcher;
SystemNavigationManager.GetForCurrentView().BackRequested += GamePage_BackRequested;
}
protected override void OnNavigatedFrom(NavigationEventArgs e)
{
base.OnNavigatedFrom(e);
SystemNavigationManager.GetForCurrentView().BackRequested -= GamePage_BackRequested;
}
You should handle the backrequest ; e.handled = true;
private async void GamePage_BackRequested(object sender, BackRequestedEventArgs e)
{
e.handled = true;
var dialog = new Windows.UI.Popups.MessageDialog("Are you sure ?");
dialog.Commands.Add(new Windows.UI.Popups.UICommand("Yes"));
dialog.Commands.Add(new Windows.UI.Popups.UICommand("No"));
var result = await dialog.ShowAsync();
}
You should add onnavigatedfrom method to unregister the event, otherwise it will trigger twice !
protected override void OnNavigatedFrom(NavigationEventArgs e)
{
if (gb.DetectPlatform() == Platform.WindowsPhone)
HardwareButtons.BackPressed -= HardwareButtons_BackPressed;
elde
SystemNavigationManager.GetForCurrentView().BackRequested -= GamePage_BackRequested;
};
}
There is no way to accomplish what you want -- the back key handler requires an immediate answer (handled or not) but the dialog is inherently async.
You can of course choose to mark the event as Handled before you show the dialog, but then if the user says "Yes" there's no way you can then navigate away. You can of course terminate the app, but that's a bad idea (see final paragraph)
That said, you don't typically need this dialog because in Windows 10, backing out of an app doesn't terminate it, it just switches to the previous app (or the Start menu). The user can trivially return to it via the task switcher (or launching it again).
My UWP application was crashing when I called MessageDialog.ShowAsync in the Application.UnhandledException event handler and this was the top result when I searched for an answer.
I resolved the issue by setting UnhandledExceptionEventArgs.Handled = true before calling MessageDialog.ShowAsync.
This is well documented in another SO question, but I didn't find that answer until after I figured out the solution because I didn't realize calling the method from Application.UnhandledException was significant.
We are currently upgrading and remodularizing our code as we transfer from 32 to 64 bit system. In due process, one of our goals is to change from an Init() function where things were added as such example.
this.Closing += new System.ComponentModel.CancelEventHandler(this.Form_Closing);
I'd like Windows events to handle these sorts of things. So I went to the Form_Closing event in the Windows Form Events and [without surprise] saw that this was not the form_closing event. My question to this is, is there any difference between what is actually going on with CancelEventArgs vs FormClosingArgs, or are these two pieces of code literally doing the same thing with one being a Component of System and one being the result of a Windows Event handling what it does best? I'm just sort of diving and indulging myself into this new project as an intern. Is it possible to just replace the CancelEventArgs with the FormClosing one without any loss of data or issues?
Code 1: CancelArgs
private void Form_Closing(object sender, CancelEventArgs e)
{
// If the user hit Cancel, just close the form.
if (this.DialogResult == DialogResult.Ignore)
return;
if (this.DialogResult == DialogResult.OK)
{
// If the address is not dirty, just cancel out of
// the form.
if (!this._editedObject.IsDirty)
{
this.DialogResult = DialogResult.Cancel;
return;
}
// Save changes. If save fails, don't close the form.
try
{
SaveChanges();
return;
}
catch (Exception ex)
{
ShowException se = new ShowException();
se.ShowDialog(ex, _errorObject);
_errorObject = null;
e.Cancel = true;
return;
}
}
Form_Closing -- Preferred Route
private void ScheduleItemDetail_FormClosing(object sender, FormClosingEventArgs e)
{
// If the user hit Cancel, just close the form.
if (this.DialogResult == DialogResult.Ignore)
return;
if (this.DialogResult == DialogResult.OK)
{
// If the address is not dirty, just cancel out of
// the form.
if (!this._editedObject.IsDirty)
{
this.DialogResult = DialogResult.Cancel;
return;
}
// Save changes. If save fails, don't close the form.
try
{
SaveChanges();
return;
}
catch (Exception ex)
{
ShowException se = new ShowException();
se.ShowDialog(ex, _errorObject);
_errorObject = null;
e.Cancel = true;
return;
}
}
}
You don't get the CloseReason property with the CancelEventArgs class, which is the only difference, since FormClosingEventArgs inherits from the CancelEventArgs class. The FormClosingEventArgs was introduced in .Net 2.0.
Alternatively, instead of using the event, you could just override the OnFormClosing method, too.
protected override void OnFormClosing(FormClosingEventArgs e) {
// your code
base.OnFormClosing(e);
}
I have two pages in my app.One is blankPage and other is basic page. On basic page I want to provide a message if a user press back button like
"Are you sure you want to quit" .If Yes then go back else remain there , this working fine by using this code
HardwareButtons.BackPressed += HardwareButtons_BackPressed;
private async void HardwareButtons_BackPressed(object sender, BackPressedEventArgs e)
{
e.Handled = true;
MessageDialog dlg = new MessageDialog("Are you sure you want to quit you will loose all your work ?", "Warning");
dlg.Commands.Add(new UICommand("Yes", new UICommandInvokedHandler(CommandHandler1)));
dlg.Commands.Add(new UICommand("No", new UICommandInvokedHandler(CommandHandler1)));
await dlg.ShowAsync();
}
private void CommandHandler1(IUICommand command)
{
var label = command.Label;
switch (label)
{
case "Yes":
{
this.Frame.Navigate(typeof(MainPage));
break;
}
case "No":
{
break;
}
}
}
But when I am pressing back button on my BlankPage this message also appears there and also appearing in all other basic page if I add more . What mistake am I doing??
You are registering hardware back button in page constructor or page load event and once this event is registered you are not unregistering this event. BackPress is app level. for correctly using this event on your desired page register Back Press event in your OnNavigatedTo override method and unregister this event in OnNavigatedFrom ovrride metho. here is how.
protected override void OnNavigatedTo(NavigationEventArgs e)
{
Windows.Phone.UI.Input.HardwareButtons.BackPressed += HardwareButtons_BackPressed;
}
protected override void OnNavigatedFrom(NavigationEventArgs e)
{
Windows.Phone.UI.Input.HardwareButtons.BackPressed -= HardwareButtons_BackPressed;
}