Hi,
I have an application and this application needs to close when the window shutdown happen. How can i detect that the system is shutting down from a C# program

Check this:
http://www.planet-source-code.com/URLSEO/vb/scripts/ShowCode!asp/txtCodeId!2185/lngWid!10/anyname.htm

Thanks

I tried to use it , but getting an error

Error	1	The type or namespace name 'Message' could not be found (are you missing a using directive or an assembly reference?)

my application code is given here

public partial class Program
    {
        static void Main(string[] args)
        {

            string regMatch = "";//string to search for inside of text file. It is case sensitive.
            string readtext = "";
            string path = "";
            bool persistantfilepresent = false;
            bool status = false;
            try
            {
                readtext = readroutetable(); // Read the windows routing table

                //path = "d:\\file.txt";
                //deletefiles(path); //Delete the  output dump file

                path = "d:\\madavas1.txt";
                deletefiles(path);  //delete madavas1 files 
                createfiles(path);  // Create a file to write to madavas1.txt.

                path = "d:\\madavas2.txt";
                deletefiles(path); //delete madavas2 files 
                createfiles(path);  // Create a file to write to madavas2.txt.

                path = "d:\\madavas1permanent.txt";
                createfiles(path);  // Create an empty file for storing the peristant route

                regMatch = "Active Routes:";
                ActiveRoutes(regMatch, readtext);//create mdavas1.txt for persistent route

                regMatch = "Persistent Routes:";
                Persistentroute(regMatch, readtext);//create mdavas2.txt for active route


                readrange();           
                currentgateway();           // Read current gateway values

                status = comparerange();       
                              }


                persistantfilepresent = checkpersitantroute();     
                writepersistantroute();
[B][I]// Here I want a while loop to check whether the system shut down is there [/I][/B] 
            }
            catch (Exception e)
            {
                Console.WriteLine("{0} Exception caught.", e);
                Console.ReadLine();
            }
        }
        /*This is the Message constant Windows sent to let the application to let it know is going to shutdown*/
        private const int WM_QUERYENDSESSION = 0x0011;
        private bool isShuttingDown = false;
        /*This is the method (WndProc) which receive Windows Messages we are overriding it to make it works as we want*/
        protected override void WndProc(ref Message m)
        {
            if (m.Msg == WM_QUERYENDSESSION)
            {
                isShuttingDown = true;
            }
            base.WndProc(ref m);
        }
        private void frmLogin_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if (isShuttingDown)
            {
                if (MessageBox.Show(this, "The application is still running, are you sure you want to exit?",
                     "Confirm Closing by Windows Shutdown", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == System.Windows.Forms.DialogResult.Yes)
                {
                    e.Cancel = false;
                }
                else
                    e.Cancel = true;
            }
        } 

    }

I have highlited where i need to put the code for shutdown and the code i added to test the shutdown

Hi,
I have an application and this application needs to close when the window shutdown happen. How can i detect that the system is shutting down from a C# program

Hi
Try this code
If you override the WndProc and intercept the WM_QUERYENDSESSION message (shown below) then you can handle shutting down.

private const int WM_QUERYENDSESSION = 0x0011;
internal static bool shuttingDown;


// In the class with the Main( ) function defined...

protected override void WndProc( ref Message m )

{

if( m.Msg == WM_QUERYENDSESSION) {

// You're shutting down

shuttingDown = true;

}


base.WndProc( ref m );

}


// Now, in your form's Closing event handler...

private void form1_Closing( object sender, System.ComponentModel.CancelEventArgs e )

{

if( shuttingDown ) {

// Do safe app close here

}

}

Hi paul,
Thanks for the reply.
i have tried wat you have suggested.
Here is my complete application

namespace ConsoleApplication1
{
public partial class Program
    {
        static void Main(string[] args)
        {

            string regMatch = "";//string to search for inside of text file. It is case sensitive.
            string readtext = "";
            string path = "";
            bool persistantfilepresent = false;
            bool status = false;
            try
            {
                readtext = readroutetable(); // Read the windows routing table

                //path = "d:\\file.txt";
                //deletefiles(path); //Delete the  output dump file

                path = "d:\\madavas1.txt";
                deletefiles(path);  //delete madavas1 files 
                createfiles(path);  // Create a file to write to madavas1.txt.

                path = "d:\\madavas2.txt";
                deletefiles(path); //delete madavas2 files 
                createfiles(path);  // Create a file to write to madavas2.txt.

                path = "d:\\madavas1permanent.txt";
                createfiles(path);  // Create an empty file for storing the peristant route

                regMatch = "Active Routes:";
                ActiveRoutes(regMatch, readtext);//create mdavas1.txt for persistent route

                regMatch = "Persistent Routes:";
                Persistentroute(regMatch, readtext);//create mdavas2.txt for active route


                readrange();           
                currentgateway();           // Read current gateway values

                status = comparerange();       
                              }


                persistantfilepresent = checkpersitantroute();     
                writepersistantroute();
// [B]Here I want a while loop to check whether the system shut down is there  [/B]
            }
            catch (Exception e)
            {
                Console.WriteLine("{0} Exception caught.", e);
                Console.ReadLine();
            }
        }
[I]// Added suggested  code here[/I]
}

i I added the code you suggested as specified above. But i got the error as metioned in previous post

Do i have to use some header file for removing the error?

It's probabbly because you have a console app and Message is part of System.Windows.Forms eg not included in a console app by default.

Even if you add the assembly reference I don't think the WndProc will work unless you have a form.

I tried to use it, but getting an error

Error 1 The type or namespace name 'Message' could not be found (are you missing a using directive or an assembly reference?)

my application code is given here

...        }
}

...

That message tells you exactly what is wrong. The complete object address is: System.Messaging.Message Put using System.Messaging; at the beginning of your code or spell it out.

It's probabbly because you have a console app and Message is part of System.Windows.Forms eg not included in a console app by default.

Even if you add the assembly reference I don't think the WndProc will work unless you have a form.

Sorry, didn't read your code carefully. You should blow up because you are trying to override code that doesn't exist. If it doesn't after you put in the using statement, you may have the event process needed to do what you want. If it does, this definitely won't work. Putting in a request for user input may trigger a "code is not responding" error asking you if you want force shut-down and may lock you out of your app.

Come to think of it, the override would probably work, it probably resides in Win32, not Forms. You can't depend on the Form closing event processor, because it doesn't exist. Note that the loop you wanted to put in can't be put in. but a regular loop should continue working if you override the closing event.

ARe you suggesting to have an application to be created with a form to resolve this issue?

Hey All.
Great help from you all.
i moved the project to a form application and it is detecting the shut down.
Thank you all for the help

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.