Handle application exit - windows-8

I want to run some cleanup code(like unregistering scheduled notifications) when a user quits the application by using the Alt-F4 or swipe down gesture. Is there any way to handle an application exit in WinJS? I've read the docs for the WinJS.Application object but don't see any methods to handle user exits.

There is no special event that indicates that an app is being closed:
There's no special event to indicate that the user has closed an app. After an app has been closed by the user, it's suspended and terminated, entering the NotRunning state within about 10 seconds. If an app has registered an event handler for the Suspending | suspending event, it is called when the app is suspended. You can use this event handler to save relevant application and user data to persistent storage.
So you'll want to handle a suspend/resume instead. The gory details for handling a suspend are here, but here's a summary:
Register for the checkpoint event that will tell your app that it's being suspended.
Save whatever data you need to save in the event handler for that event.
Release resources, suspend notifications, etc. in the event handler as well.
On resume, you can check if the app was closed by the user using the ApplicationExecutionState enum. That may or may not be relevant to you, since there doesn't seem to be a way to differentiate why checkpoint event was fired and your only option is to save your state in the event handler no matter why it happened.
There are additional suspend/resume guidelines here, and you may find this sample app helpful.

Related

WMP interfacace is blocking WMP from user interaction

My MFC program remotes a WMP instance to catch WMP events and is using IWMPCore, IWMPCore3, IWMPPlaylistCollection, IWMPMediaCollection to interact with WMP using COM. The remote instance is working find and it is avle to catch the events, but when I started fetching all the details of all songs(almost 5100 songs), WMP stops responding until my application fetches all the songs and release all the above instance. Can anyone please help me out with the issue and how can it be fixed?
WMP ActiveX control is an STA COM object, so all interaction (method calls) goes through instantiation thread, which is in most cases the UI thread. That is, whatever you do with the interfaces, the calls block GUI for the time of the call.
You need to either pump window messages in the middle of your activity to unblock UI (show progress and let user hit Cancel button), or create a worker thread initialized as STA and obtain the collection details using a secondary invisible instance of WMP there.

global startup and shutdown events when application starts and exist

I need to write a log when the application starts and exits. Obviously when it starts it easy to write the log. But a user can close an application in multiple ways, even shut it down in task manager. is there sort of a global event when shutting an application down it will call a specific event from anywhere and I can add my logging code?
In visual Studio, go to the project properties window, Application tab. AT the bottom is a button labelled 'View Application Events' This takes you to a code view where you can add handlers for the application events including the shutdown event. However, this isn't always fired if your application crashes ^H^H^H^H^H closes in an 'unusual' way.
The startup event is useful too - you could put your startup logging code in there- we use it a lot to put in all the application setup code, with only a splash screen showing, then when the startup code completes the main window will pop up.
Finally, the Unhandled Exception event is a handy place to put a final catch-all backstop error handler

How to update a NSTextField Value during an action?

I am running a lengthly task in an Action and I would like to have a display of where I am at. For that I created a Text Field and I tried it with setStringValue:
[textField setStingValue: [NSSting stringWithFormat:#"%ld",currentValue]]
The code works but unfortunately it is not updating the NSTextField after every iteration but rather when the whole Action is done.
What am I doing wrong?
This is because applications with the Cocoa framework use an event loop to perform operations, and events occur in a completely serial fashion.
An event is basically any kind of action that the framework designer could not predict or found convenient to have run in a delayed manner. Since you can't predict when clicks will be performed, they need to be considered events; and for efficiency reasons (since you don't want to repaint a component multiple times if you don't need to), the repaint actions are events too.
Your action runs in response to a user event (for instance, a click on a button is an event) and therefore blocks all other events waiting in the queue until it's complete. However, components are repainted in response to a different, framework-triggered event, and as such the text field must wait until your action completes to repaint itself. This is why you cannot visually change the value of a text field from inside an action.
In order to notify your user of the progress of your task, you'll need to run it on a different thread. There's a lot to say about threads, so you should probably read some about them. I'm also sure that there are plenty of examples of how to run a long action in a background thread and update the UI accordingly for Cocoa all over the Internet.
When you click on a UI component, and it enters the Action block, the code is running on the main thread, the same thread that is painting the UI. If you run a long running operation in that block, it isn't going to paint until you are done because it is busy doing whatever you have it doing - you have hijacked the paint thread.
As said elsewhere, you need to spawn another thread, and then have the new thread perform the long running operation, and occasionally send messages to have the UI be updated by the main thread.
As a next step, go read the Apple documentation on NSThread, specifically:
+ (void)detachNewThreadSelector:(SEL)aSelector toTarget:(id)aTarget withObject:(id)anArgument
Be aware that threading is a non-trivial domain area, and be ready for some wierd behavior if you aren't careful.

What is event loop in ios life cycle and what is its usage and what it does?

I need to know what the event loop in the ios life cycle does?.
Can any one suggest me regarding this??
The best answer is probably the one provided by Apple in the "Main event loop" section of the Cocoa Application Competencies for iOS document.
In the main event loop, an application continuously routes incoming events to objects for handling and, as a result of that handling, updates its appearance and state. An event loop is simply a run loop: an event-processing loop for scheduling work and coordinating the receipt of events from various input sources attached to the run loop. Every thread has access to a run loop. In all but the main thread, the run loop must be configured and run manually by your code. In Cocoa applications, the run loop for the main thread—the main event loop—is run automatically by the application object. What distinguishes the main event loop is that its primary input source receives events from the operating system that are generated by user actions—for example, tapping a view or entering text using a keyboard.
Incidentally, if you're relatively new to iOS development, I'd really recommend a read of this document, as it'll answer a lot of questions you probably have.

Form not refreshing after ShowDialog (Compact Framework)

I'm having a weird issue with form painting in the Compact Framework. I have a login dialog that is basically a small form that is opened on top of another using ShowDialog. When a card is swiped, the login dialog is supposed to close, then some login tasks are performed and then the form behind it should be activated. The problem is that the form behind the login dialog is not being refreshed and so the login dialog will not be removed until after the form behind is refreshed by some user action. This is probably due to the heavy processing that goes on in the login tasks part, but I've not found a way to solve this.
Basically, I want a way to force the application to close the dialog and paint everything again, before performing the heavy login tasks. I've tried numerous refresh methods without any luck:
Form loginDialog = new Form();
DialogResult result = loginDialog.ShowDialog();
loginDialog.Dispose();
//I've tried everything at this point to get the form to refresh before performing
//login tasks
this.Refresh();
this.Invalidate();
Application.DoEvents();
PerformHeavyLoginTasks();
Does anyone know what could be going wrong? Thanks
Ok I figured this out. The problem was with a custom control on the background form that manually paints itself using rectangles and such. I think this is a compact framework bug since I called Refresh and Invalidate on that control as well and it should've repainted. I had to create a method that would call the control's OnPaint override directly since Invalidate and Refreshed were pretty much ignored.
The issue, I believe, is that you're not fully understanding what's going on system-wise here.
When your fore window (the Dialog) is dismissed, the background window (the Form) is given focu and tol to repaint the clipping region where the dialog was. This happens via a PostMessage call, which sends a Windows Message that has to be popped, translated and dispatched down in the bowels of the Application.Run call.
This is, by design, a fairly slow process as the UI should not be preempting things that are important.
If you are doing heavy processing immediately after that PostMessage happens, the processing of those windows messages can often be slowed, ending up with the UI appearing "locked" or drawing really slowly. This is exacerbated if the processing you're doing is on the same thread as the UI.
Why are your efforst not making things better?
Calling Refresh simply sends another message. That message now gets in line for processing, so it would actually make things worse.
Calling Invalidate does pretty much the same this as Refresh, just asynchronously. Again, it makes things worse.
DoEvents tells the message pump to pop, translate and dispatch a message. That dispatch still has to be processed on the UI thread, so noting is going to happen until the thread has time to do the work (i.e. after your processing)
So how do we "fix" this?
The first step is often to put the processing on a separate thread to allow the scheduler to round-robin tasks between the UI and processing threads, up to the default quantum. Thgis means that the processing can only starve the UI for a maximum of 100ms before some sort of drawing is allowed to occur (assuming equal thread priority).
new Thread(PerformHeavyLoginTasks)
{
IsBackground = true
}.Start();
You can go a step further and give the UI a "jump start" on the processing (of 10ms in this example):
new Thread(new ThreadStart(delegate
{
Thread.Sleep(10);
PerformHeavyLoginTasks();
}))
{
IsBackground = true
}.Start();
Of course this may mean you need to now handle the next "display" asynchrously if the UI you want to display is dependent on the processing result. There are plenty of online resources for async patterns, so I won't beat that dead horse here.