Session Ending event not working - c#

I want to let the user decides if he wants to do a last request at my app when the the Windows is shutting down or logging off. So I am using the "SessionEnding" event.
The following code is triggered but doesn't work. Here is the simplest example:
public App()
{
this.SessionEnding += App_SessionEnding;
}
void App_SessionEnding(object sender, SessionEndingCancelEventArgs e)
{
e.Cancel = true;
}
I am afraid that I've used a boost program before in my computer (like CCleaner), and somehow it deactivated this event. =O
When I add a MessageBox to the event, and I request to log off my computer, then the MessageBox appears, but I don't have time to click somewhere because after 1 second, the system log off. The system seems to not be waiting for my application.
Obs: I am using Windows 7.

I tried a sample of your code without success ... however I put this into my main window that causes the application to close and the MessageBox was displayed indefinitely until I clicked close. Could this help?
protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
{
MessageBox.Show("Blah", "Blah", MessageBoxButton.OK);
base.OnClosing(e);
}

Try overriding the event handler that's already there.
https://wpf.2000things.com/2011/01/25/197-override-application-class-methods-for-standard-events/
public partial class App : Application
{
protected override void OnSessionEnding(SessionEndingCancelEventArgs e)
{
// Always call method in base class, so that the event gets raised.
base.OnSessionEnding(e);
// Place your own SessionEnding logic here
}
}

Related

BackRequested event handler event.Handled is ignored

So, as per the docs I attach a handler when I navigate to a page:
protected override void OnNavigatedTo(NavigationEventArgs e) {
/* Attach back listener to handle the back press */
SystemNavigationManager.GetForCurrentView().BackRequested += NavigationPage_BackRequested;
...
}
And I detach it when leaving:
protected override void OnNavigatingFrom(NavigatingCancelEventArgs e) {
SystemNavigationManager.GetForCurrentView().BackRequested -= NavigationPage_BackRequested;
e.Cancel = false;
}
And I mark the event as handled to prevent the system from handling it:
private void NavigationPage_BackRequested(object sender, BackRequestedEventArgs e) {
e.Handled = true;
}
But the system still handles the back click and I get navigated away. Why?
Your code shown above is working fine (tested on my machine), but the big question is: do you try to cancel a system provided navigation event or a Frame.GoBack() event implemented by the software button of your application?
SystemNavigationManager: Provides a way for an app to respond to system provided back-navigation events.
If you look at the backwards navigation documentation, only certain back buttons (hardware/software) are system provided events, e.g. the software button at the bottom in Tablet mode.
However quite a few project templates (in Visual Studio or from MVVM libraries) also provide a software back button (quite often at the top left) and wire this event to the Frame.GoBack() method. This is NOT a system provided event and can't be cancelled this way. Reasoning: You (or the framework used) is calling the GoBack() explicitly, so why would it have to be cancelled in this scenario.

Check if user came to app by clicking on SecondaryTile

I want to know if user opened app by clicking SecondaryTile (and also which one was clicked).
Now I have OnNavigatedTo method:
protected override async void OnNavigatedTo(NavigationEventArgs e)
{
if (!String.IsNullOrEmpty(e.Parameter.ToString()))
{
//e.Parameter is not null, LiveTile was used
//do something
}
else
{
//No of SecondaryTiles were clicked
}
}
This of course works, but only if app was previously closed. But when app was previously opened, runs in background and user click on LiveTile, then app is being shown but this method is not executed.
How can I handle this scenario?
MSDN: Override the OnLaunched method to perform any general app initialization that should occur only when the user launches your app normally (for example, by tapping the app tile).
You should override or update the OnLaunched event to track app activation moment and analyze corresponding arguments (app.xaml.cs file).
In short, if you look on how OnNavigatedTo event is rised -- it comes from the OnLaunched event that checks whether rootFrame's content already exists or not:
protected override void OnLaunched(LaunchActivatedEventArgs e)
{
...
if (rootFrame.Content == null)
{
// When the navigation stack isn't restored navigate to the first page,
// configuring the new page by passing required information as a navigation
// parameter
rootFrame.Navigate(typeof(MainPage), e.Arguments);
}
...
}
As you may imagine in your scenario it is not true, so navigation event never happens.

Alarm without message dialog

I would like to make and App that when users set an alarm (like wake up alarm) and alarms sounds, doesnt show a message dialog to confirm and stop the alarm.
On web I have discovered some methods called Obscured and UnObscured that fired when the message's alarm shows, but the message still showed!
In Code:
public OverAlarmPage()
{
InitializeComponent();
PhoneApplicationFrame phoneAppRootFrame = (Application.Current as App).RootFrame;
phoneAppRootFrame.Obscured += OnObscured;
phoneAppRootFrame.Unobscured += Unobscured;
}
void OnObscured(Object sender, ObscuredEventArgs e)
{
txtStatus.Text = "Obscured event occurred";
}
void Unobscured(Object sender, EventArgs e)
{
txtStatus.Text = "Unobscured event occurred";
}
I just want to make stop the alarm sound with the vibrating of mobile (with gyroscope) but without the hell message!
There are any solution or is this a O.S feature that i cant touch?
The built in notification classes (Alarm and Reminder) don't support any customization of the UI that is displayed when they are triggered.
The only alternative I can think of would require the application to remain running (possibly under the lock screen) and then you just play the sound from the app at the appropriate time.
Obviously this requires that the app remain running though.
Other than that you will be prevented from trying to create the behaviour you are after.

SystemEvents.SessionEnding not firing

I am developing an windows forms application in c# .net 4.0.
I want to capture windows logoff event.
Here is the code:
public Form1()
{
InitializeComponent();
SystemEvents.SessionEnding += (s, e) =>
{
if (e.Reason == SessionEndReasons.Logoff)
{
MessageBox.Show("LogOff");
}
else if (e.Reason == SessionEndReasons.SystemShutdown)
{
MessageBox.Show("ShutDown");
}
};
}
Why isn't my sessionEnding firing?
It depends on the configuration that is set on gpedit.msc.
Open gpedit.msc, navigate to Computer Configuration > Administrative Templates > System > Shutdown Options and choose Turn off automatic termination of applications that block or cancel shutdown. Since mine laptop configure make it automatic shutdown, so it will never fire session ending
Perhaps you can move your code above into entry point of its windows (in the main).
Perhaps you can override windows message. You can see it in MSDN library documentation.
http://msdn.microsoft.com/en-us/library/microsoft.win32.systemevents.sessionending.aspx
Shutdown message pump has been re route by other software and not re route to your apps
This could be useful to someone.
if form close event is included
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
e.Cancel = true;
}
then SessionEnding will not be fired, i just encoutered this problem and rectified it
void SystemEvents_SessionEnding(object sender, Microsoft.Win32.SessionEndingEventArgs e)
{}
here i need to prevent Form close upon Alt+F4 command, so i added this form closing event this resulted in this issue. so we can integrate session ending event in form close event. Option 2 in Refered from stackoverflow answer

c# WinForms form still closes after setting e.Cancel = true in Form_FormClosing event

This is the code in question:
private void FormAccounting_FormClosing(object sender, FormClosingEventArgs e)
{
Properties.Settings.Default.FormAccountingLocation = this.Location;
Properties.Settings.Default.Save();
if (IsEditing)
{
MessageBox.Show("Please save or cancel open transactions before closing the accounting window.", "Open Transactions", MessageBoxButtons.OK, MessageBoxIcon.Information);
e.Cancel = true;
}
}
I've added breakpoints to the e.Cancel = true; line to ensure it's being executed.
The form closes immediately after clicking Ok.
Here's the code that calls FormAccounting:
private void buttonAccounts_Click(object sender, EventArgs e)
{
FormAccounting NewFormAccounting = new FormAccounting();
NewFormAccounting.Show();
}
Canceling the form close event works to prevent:
User closing the form
Application.Exit from exiting the application
Code from calling Form.Close on the form
But it does not work to prevent:
User closing application's main form
Code calling Form.Dispose on the form
Code calling Form.Close on the application's main window
The last 3 cases don't even trigger the form close event on the non-main form, so the form goes away without a chance to cancel it. Perhaps your application is causing the form to first close in one of the first 3 ways, which triggers the event, and then in one of the second 3 ways (or something similar), which does not trigger the event and forces the form closed anyway.
Edit:
Add this function to your form's code and it will allow you to review in the debugger what the call stack looks like when your window is getting closed so you can see what is actually causing it:
protected override void DestroyHandle()
{
System.Diagnostics.Debugger.Break();
base.DestroyHandle();
}

Categories

Resources