473,837 Members | 1,436 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Application.Run () never returns when windows is shutting down?

Hi,

I have a problem with Application.Run () when Windows is shutting down.
Please have a look at the copy&paste example program below.

The application has no forms. It has only got a notify icon in the
system tray and it uses Application.Run () to keep the message loop
running. When the user clicks the icon, the application should shut down
and exit. So far that works fine.

The problem is: when the user logs out while the program is running, the
Application.Run () never returns. Windows just pulls the program out of
RAM and kills it.

How can I make the Application.Run () method return on Windows shutdown
and gracefully close the application?

thanks,
Max

using System;
using System.IO;
using System.Windows. Forms;

namespace TestNotifyIcon {
public class MyApp {
[STAThread]
private static void Main() {
NotifyIcon ni = new NotifyIcon();
Form f = new Form();
ni.Icon = f.Icon;
ni.Click += new EventHandler(ni _Click);
ni.Visible = true;

Application.Run ();

// these last few lines of code don't get executed when windows
// shuts down or when the user logs off.
using (StreamWriter sw = new StreamWriter(@" c:\done.txt")) {
sw.Write("done" );
}
}

private static void ni_Click(object sender, EventArgs e) {
Application.Exi t();
}
}
}
Jul 3 '06 #1
4 3413
Markus Stoeger wrote:
Hi,

I have a problem with Application.Run () when Windows is shutting down.
Please have a look at the copy&paste example program below.

The application has no forms. It has only got a notify icon in the
system tray and it uses Application.Run () to keep the message loop
running. When the user clicks the icon, the application should shut down
and exit. So far that works fine.

The problem is: when the user logs out while the program is running, the
Application.Run () never returns. Windows just pulls the program out of
RAM and kills it.

How can I make the Application.Run () method return on Windows shutdown
and gracefully close the application?

thanks,
Max
<snipeddy-doo-dah>

Hi Markus,

Try subscribing to the Application.App licationExit event, and see if that
gets fired. Also take a look at the Application.Thr eadExit event, they may
be useful.

--
Hope this helps,
Tom Spink
Jul 3 '06 #2
Tom Spink wrote:

Hi Tom,
Try subscribing to the Application.App licationExit event, and see if that
gets fired. Also take a look at the Application.Thr eadExit event, they may
be useful.
I already tried that.. doesn't work. The program gets killed before
these events are fired.

I also tried to implement the IMessageFilter interface, but I get no
useful "shutdown"-messages (like WM_QUERYENDSESS ION or WM_ENDSESSION)
either.

Any other ideas? Seems too simple to be impossible...

thanks,
Max
Jul 3 '06 #3
I do this, but only under 98 (mine's a service under NT+). I use the
sessionEnding event - it seems to work on system shutdown, but doesn't if the
app is terminated using CTRL-Alt-Del.
--
Dave
"Markus Stoeger" wrote:
Tom Spink wrote:

Hi Tom,
Try subscribing to the Application.App licationExit event, and see if that
gets fired. Also take a look at the Application.Thr eadExit event, they may
be useful.

I already tried that.. doesn't work. The program gets killed before
these events are fired.

I also tried to implement the IMessageFilter interface, but I get no
useful "shutdown"-messages (like WM_QUERYENDSESS ION or WM_ENDSESSION)
either.

Any other ideas? Seems too simple to be impossible...

thanks,
Max
Jul 4 '06 #4
"Markus Stoeger" <sp******@gmx.a twrote in message
news:eX******** ******@TK2MSFTN GP03.phx.gbl...
I have a problem with Application.Run () when Windows is shutting down.
Please have a look at the copy&paste example program below.

The application has no forms. It has only got a notify icon in the system
tray and it uses Application.Run () to keep the message loop running. When
the user clicks the icon, the application should shut down and exit. So
far that works fine.

The problem is: when the user logs out while the program is running, the
Application.Run () never returns. Windows just pulls the program out of RAM
and kills it.

How can I make the Application.Run () method return on Windows shutdown and
gracefully close the application?
My apologies for the very late reply. Perhaps no one even cares about the
answer at this point. :( Still, I just came across the post and figured I
might as well put my two cents in, since I just ran into this myself.

Anyway, the short answer to your question is that you can't make the
Application.Run () method return on Windows shutdown.

In order to gracefully shutdown your application even when the user is
logging off (due to a shutdown or simply due to logging out), one has to add
a handler for the SessionEnded event (which corresponds to the WM_ENDSESSION
window message).

If one looks at the documentation for the WM_ENDSESSION message, one finds
this text:

the session can end any time after all applications have
returned from processing this message

(see http://msdn.microsoft.com/library/en...endsession.asp
for the complete reference)

The upshot of this is that after your program returns from handling that
message (whether by the default window proc or by your own custom handler),
Windows is free to forceably terminate your program without warning (no
programs can be left running after the session has ended, and the docs give
no guarantee that the session will stay around long enough for your program
to exit normally).

Any processing you want to do before being terminated, you have to do when
the WM_ENDSESSION message is sent (in .NET, that's the SessionEnded event),
or possibly when the WM_QUERYENDSESS ION message is sent (SessionEnding) .

IMHO, this is very poorly documented, in spite of the fact that I suspect
lots of applications implicitly or explicitly assume that they will always
be terminated through the usual means (except when the user explicitly
forceably terminates the application, via Task Manager for example).
Lengthy, possibly uninteresting, musings follows... (the above is all you
really need to know)

My first reaction after figuring this out was "what the hell?" But after
thinking about it a little more, it makes sense to me. Applications are
sent a WM_QUERYENDSESS ION message before Windows even decides to actually
end the session. At that point, applications have the opportunity to save
data, ask the user if they want to discard changes, etc. The application
can request that the session NOT be terminated by cancelling the event.
This is the point at which the OS is "being nice", and if the application
responds by telling the OS that it's okay to exit, the OS assumes it was
telling the truth.

So, the application gets one last message, once the OS has figured out
whether it's actually ending the session (note: an application that has not
cancelled the WM_QUERYENDSESS ION message may still be terminated!), which is
the WM_ENDSESSION message. The OS makes sure that it doesn't have to wait
some indeterminate time for programs that lied and said they were ready to
exit by simply saying "I'm not guaranteeing you ANY time to exit
normally...you had your chance to clean up, I waited for you then, and I'm
not going to wait any longer once you tell me you're done".

This does make things harder on the application developer, but the big
advantage is that it makes the rules for shutting down VERY clear. Save
state if necessary when the WM_ENDSESSION message comes, at the latest, and
don't expect to be able to execute any more code after you return from
handling that message.

Anyway, no...this isn't the only way that Microsoft could have addressed
this issue, but I do see the benefit in the approach they took. Many
Windows applications are essentially stateless; that is, they do something
while you're logged in and running them, but you can safely terminate them,
gracefully or otherwise, at any time. For the subset (significant, to be
sure) of programs that are stateful, whether because they are document
based, or are trying to do something with the disk, or whatever, have
specific rules allowing them to have a say in how and when the OS shuts them
down, separate from the usual method of exiting. This allows the OS to
treat each application appropriately without having to wonder which ones
need special handling and which ones don't. Need special handling? Respond
to the ...ENDSESSION messages.

Still, I wish it were better documented (especially in the C# sections,
which don't even have the minimal reference to early termination that the
regular Platform SDK docs do). When I was first researching this, I saw
plenty of messages in various places by people who were puzzled by the
behavior, and not a lot of answers. :(

Pete
Sep 7 '06 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
3483
by: kuldeep | last post by:
Hi all, I have a application developed in C# .net. The problem I face is I am unable to shutdown my machine when the exe is running. Windows is unable to close this exe an shut down. Can anyone help. Regards, Kuldeep Pawar
3
2955
by: Claire | last post by:
Windows refuses to close down if my applications main form is hidden and there's a notify icon in the system tray. If I restore the form, then shutting down Windows succeeds. If I comment out the code in "frmOptions_Closing" then run and hide the application, Windows shuts down normally. I think there was a way to find out what was causing an application to close down - api call? Is there anything in .net that I can query My code is...
3
2040
by: Jeff Greenland | last post by:
Hello everyone, I am having problems with Timers in a web application. They just seem to stop running after 15 minutes or so. My web application is set up like this: When a user hits a page in the site, that page (.aspx) instantiates a compiled class (.DLL). The instantiation process creates a Timer that runs in the background to perform tasks every so often (such as notifying clients
2
4780
by: Alex | last post by:
My Problem is that although i have added a handler to Application.ThreadException and it works fine for my application exceptions, it does not fire if an exception is generated inside an event handler of my App. eg. If i throw a exception inside DragDrop, or MouseDown of an event the ThreadException does not fire !! Any ideas ???
7
6719
by: Ralf Gedrat | last post by:
Hello! I have some Vb.Net applications, which are terminated at indefinite times without message. If I call in the program regulated system.GC.Collect, then the program is terminated here sporadically without message. It's not possible to debug in visual studio, i get no exceptions (application is terminated unexpectedly without message).
12
17068
by: Patrick Dugan | last post by:
I have an vb.net application that is a module that uses a "application.run" in the sub main to start. There is no form involved (just a system tray icon) How can you detect when the application is being closed? It is easy enough if the user selects "exit" from this tray icon but how can you detect if Windows is closing the program down? Normally I would simply do something in the Form.Closing event but without a form how can you...
8
6056
by: mike2036 | last post by:
I have an application (that has unmanaged code) and when I launch it without 'FullTrust' permissions (LocalIntranet_Zone), it crashes. When I set 'FullTrust' permissions, it launches fine. Is there a way I can compile the application such that it won't even attempt to launch without correct permissions instead of just crashing? Thanks for any help. -Mike
0
1351
by: Kevin A | last post by:
The problem is that the web application mysteriously shuts down (ending all sessions) due to a supposed 'configuration change'. By using ASP.Net Health Monitoring we can determine that the application occasionally raises a "Application is shutting down. Reason: Configuration changed." event during normal application usage. The only known way to duplicate this event is to manually save the web.config, which correctly triggers the event as...
3
3188
by: leocwh | last post by:
Dear all, I would like to know how to run the execuatable before windows shutting down. Here is my simple code: Private Sub Command1_Click() Shell "C:\abc.bat", vbNormalFocus End Sub Private Sub Form_QueryUnload(Cancel As Integer, UnloadMode As Integer)
0
9843
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, weíll explore What is ONU, What Is Router, ONU & Routerís main usage, and What is the difference between ONU and Router. Letís take a closer look ! Part I. Meaning of...
0
9683
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10882
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10577
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10630
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
7005
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5851
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4476
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
4045
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.