Results 1 to 38 of 38

Thread: Detect System Shutdown

  1. #1

    Thread Starter
    Fanatic Member LITHIA's Avatar
    Join Date
    Dec 2002
    Location
    UK, England
    Posts
    575

    Detect System Shutdown

    Hi,

    Is there a way to detect if the computer is attempting to shut the system down, log off or restart?

    I have some API's but I don't know how to use them really...

    What I need to do, is for my program to detect if an application is trying to shutdown, log off or restart and cancel it straight away.

    Then I can ask the user what to do basically; accept it or refuse it.

    Thanks for the help, I really appreciate it.

  2. #2
    KrisSiegel.com Kasracer's Avatar
    Join Date
    Jul 2003
    Location
    USA, Maryland
    Posts
    4,985
    Why not just disable the controls to allow the user to shutdown, and then use a program which would allow them to?

  3. #3
    Frenzied Member Shawn N's Avatar
    Join Date
    Dec 2001
    Location
    Houston
    Posts
    1,631
    Kasracer:

    He's saying he doesn't want applications to be able to shutdown the computer - only his app.

    LITHIA:

    What APIs are you trying to use?
    Please rate my post.

  4. #4
    Member
    Join Date
    May 2003
    Posts
    58
    Try this:

    Code:
     
        Dim sysevt As SystemEvents
    
        Private Sub SessionEndingHandler(ByVal sender As Object, ByVal reason As SessionEndingEventArgs)
            Dim r As DialogResult
            r = MessageBox.Show(reason.Reason.ToString, Convert.ToInt32(reason.Reason).ToString, MessageBoxButtons.YesNo, MessageBoxIcon.Question)
            If r = DialogResult.No Then
                reason.Cancel = True             
            End If
        End Sub
    
        Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Load        
            AddHandler sysevt.SessionEnding, AddressOf SessionEndingHandler        
        End Sub
    To test it, u need to compile this program into exe file. Run this program before u run any other programs, otherwise all applications that run before it will be terminated. Just in case, u might want to run VS IDE in debug mode to prevent PC from shutting down.

  5. #5
    Frenzied Member Shawn N's Avatar
    Join Date
    Dec 2001
    Location
    Houston
    Posts
    1,631
    Volvere's coding did not work for me, but I did find this.
    Please rate my post.

  6. #6

    Thread Starter
    Fanatic Member LITHIA's Avatar
    Join Date
    Dec 2002
    Location
    UK, England
    Posts
    575
    thanks for the help! Ill try them out when i get home!

    That SessionEnding Event looks good from the MSDN, thanks Shawn

  7. #7

    Thread Starter
    Fanatic Member LITHIA's Avatar
    Join Date
    Dec 2002
    Location
    UK, England
    Posts
    575
    No sorry, I don't know how I would adapt the code on the MSDN.

    I need it to constantly detect a system shutdown (in a module) and if it detects one, it will pause it and view a form where I can get the user to say what they want to do.

    If I get code which can't pause it, but cancel it instead, Ill have to have a way to detect what type of end session it is, whether its a shutdown, logoff or restart so I can re-instate it if the user accept its.

    Thanks

  8. #8
    Member
    Join Date
    May 2003
    Posts
    58
    have u tried out the codes I posted?
    SystemEvents class is under Microsoft.Win32 namespace, u need to import that namespace to compile it.

    I have tested it again this morning and it works. However, there is a limited time for about 5 to 10 seconds before the application is forced to close and shutdown the system.

    If you commented out the

    'Dim r as Dialogresult
    'r = Messagebox.show....
    'If r = DialogResult.No then
    reason.Cancel = True
    'End If
    statements, then your PC can never shutdown unless u unplug the power .

    Compile this program to exe and run this program only, then shutdown your PC, see what will happen.

    Good luck.

  9. #9

    Thread Starter
    Fanatic Member LITHIA's Avatar
    Join Date
    Dec 2002
    Location
    UK, England
    Posts
    575
    thnx, ill try it out

    the only problem is, I am not asking the user to specify if to allow the shutdown or not in a msgbox, im doing it in a seperate form which looks nice

    Two buttons, accept and deny. any idea? tnx
    Last edited by LITHIA; Nov 24th, 2003 at 04:49 AM.

  10. #10
    PowerPoster
    Join Date
    Mar 2002
    Location
    UK
    Posts
    4,780
    If you have a form in your app, you can just paste this in:


    Code:
    #Region "Exit Windows"
        Const WM_ENDSESSION As Integer = &H16
        Const WM_QUERYENDSESSION As Integer = &H11
        Protected Overrides Sub WndProc(ByRef e As Message)
            MyBase.WndProc(e)
            If (e.Msg = WM_QUERYENDSESSION) Then
                bolClosing = True // Trying to do the closing thing, change this to do your action
            End If
        End Sub
    #End Region

  11. #11

    Thread Starter
    Fanatic Member LITHIA's Avatar
    Join Date
    Dec 2002
    Location
    UK, England
    Posts
    575
    Sorry for the delay in a response, I have been busy correcting an error in an another aspect of the program, which is ok now!

    Ill just try out the methods here and incorporate them into the program and tell you what I come up with.

  12. #12

    Thread Starter
    Fanatic Member LITHIA's Avatar
    Join Date
    Dec 2002
    Location
    UK, England
    Posts
    575
    your code did work after some persuasion wolvere.

    The only problem is, I want the user to specify if they want to allow or disallow whatever end session it is.

    So if a program attempts to shutdown the computer, my program stops the shutdown, pops a form up and asks if you want to shutdown the computer. If you click allow, the program shuts the computer down itself. If you click disallow, it hides the form and does nothing as its already canceled the shutdown.

    This also applys for logoff or restart.

    Any ideas how I would go about that withy your code? The thing I need to know is how to identify what type of endession it is, like:

    If EndSession = Logoff Then LogoffFunction
    If EndSession = Shutdown then ShutdownFunction

    etc, understand?

    I will worry about the code to make my program actually logoff or shutdown the computer itself later. And I already have a Boolean ready to prevent the program preventing itself from ending the session

    Thanks

  13. #13
    Your Ad Here! Edneeis's Avatar
    Join Date
    Feb 2000
    Location
    Moreno Valley, CA (SoCal)
    Posts
    7,339
    You should be able to use this work around intended for restoring the UnloadMode type effect.
    http://www.vbforums.com/showthread.p...hreadid=201384

    That should work in a Module too and tell you why the application is being closed. If it were a form you could just cancel the close to cancel the shutdown.

  14. #14

    Thread Starter
    Fanatic Member LITHIA's Avatar
    Join Date
    Dec 2002
    Location
    UK, England
    Posts
    575
    thanks but its not what im looking for. I need to use API to work with EndSession, a bit like this:

    VB Code:
    1. 'In general section
    2. Const EWX_LOGOFF = 0
    3. Const EWX_SHUTDOWN = 1
    4. Const EWX_REBOOT = 2
    5. Const EWX_FORCE = 4
    6. Private Declare Function ExitWindowsEx Lib "user32" (ByVal uFlags As Long, ByVal dwReserved As Long) As Long
    7. Private Sub Form_Load()
    8.     'KPD-Team 1998
    9.     'URL: [url]http://www.allapi.net/[/url]
    10.     'E-Mail: [email][email protected][/email]
    11.     msg = MsgBox("This program is going to reboot your computer. Press OK to continue or Cancel to stop.", vbCritical + vbOKCancel + 256, App.Title)
    12.     If msg = vbCancel Then End
    13.     'reboot the computer
    14.     ret& = ExitWindowsEx(EWX_FORCE Or EWX_REBOOT, 0)
    15. End Sub

    but not that if you understand... Heres my question again:

    The thing I need to know is how to identify what type of endession it is, like:

    If EndSession = Logoff Then LogoffFunction
    If EndSession = Shutdown then ShutdownFunction

    Thanks

  15. #15
    Your Ad Here! Edneeis's Avatar
    Join Date
    Feb 2000
    Location
    Moreno Valley, CA (SoCal)
    Posts
    7,339
    Sorry can't help you with that, but this is why I posted what I did. I thought you just needed the ability to catch system shutdown and if desired cancel it. You can do that with the code in the link and a form (not sure how to cancel it without a form). When the application is closed via whatever means - TaskManager, System Shutdown, Close Button, Code - it fires the Closing event of the form at which point you can determine what caused the close and cancel it if you want. If System Shutdown is called and the form closing event cancels the close it will prevent the system from shutting down.

  16. #16

    Thread Starter
    Fanatic Member LITHIA's Avatar
    Join Date
    Dec 2002
    Location
    UK, England
    Posts
    575
    i seriously would not want to rely on that method myself... I would have expected windows to identify the program as 'Not Responding' if you didnt allow or disallow the shutdown within a few seconds.

    I really would prefer API in what I am doing, if I was just making a program which asked for you to save your work before you shut down, that would have been fine - but I am not so I really want to use the method I have got.

    Thanks for the help - its appreciated

  17. #17
    New Member
    Join Date
    Nov 2003
    Location
    Illinois
    Posts
    11

    TrojanHorse

    Ut-oh... I can just smell somebody making a trojan horse with this method. Also, I would like to add that I just got a virus scan yesterday. Before I had it I had a weird virus/trojan or something of that matter on my computer that would not let me log out, and to shutdown my computer, I had to switch out of my name, go to the left bottom corner and press "Shutdown". I couldn't do it straight from my name. After I got my virus scan, I immediatly did a scan and found 1500+ viruses on my computer, one of them, a super virus, which i believe was causing the problem. It took aproxamatly 2 hours to delete, but it isn't comming back, so the wait was long, but in the end, I regot the feature to logg off of windows from my name, and shut it down. Also, untill I got my virus scan(Norton SystemWorks 2004) I was unable to program. I had VB.Net since augest, but because I had installed a trial version of Norton SystemWorks2004 on my computer right after I finished building it with my brother, I forgot to turn off Symantec Script Blocking, and when my trial ran out and I tried booting VB.Net up for the first time, I was disapointed to find that Symantec Script Blocking had detected a script on VB.Net(Devenv.exe) and wouldn't let me open VB.Net. Well, after finnally being able to start VB.Net last night, and completing my very first VB.Net program this morning, I am a happy camper :Þ.
    Later,
    .:-|[_| . INJECTION . |_]|-:.
    \/\The Conscience of a Hacker/\/

    by

    +++The Mentor+++

    Written on January 8, 1986
    =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
    <cut by admin -- too long>

  18. #18

    Thread Starter
    Fanatic Member LITHIA's Avatar
    Join Date
    Dec 2002
    Location
    UK, England
    Posts
    575
    somone could, but i am definatly not. The code already prevents the user for shutting down, restarting or logging off, so if i was making trojan/virus, i cud stop there - but as im not, i still need help on what i asked.

    please somone help, thanks

  19. #19

    Thread Starter
    Fanatic Member LITHIA's Avatar
    Join Date
    Dec 2002
    Location
    UK, England
    Posts
    575
    wow, no reply... i seriously dont want to have to end this project im making, can somone please just help here - or give me some idea of where i can go to get some help? I am so close to having it finished.

  20. #20
    Member
    Join Date
    May 2003
    Posts
    58
    ok, what I understand so far is that, u need to catch the shutdown(logoff, shutdown or restart) event. Then u want to allow the user to accept it or refuse, and the user is given unlimited time to decide his decision.

    If thats what u want, u can do the following:
    1. Catch the shutdown event and cancel it straight away.
    2. Show the available options to user. Since the shutdown has been cancelled, it will allow the user to have unlimited time to make the decision.
    3. After finish processing the decision, re-fire the shutdown event if it is required.


    YOU WILL NEED TO MODIFY THE EXAMPLE BELOW ACCORDING TO UR NEED. To test it, u need to compile to exe then run it before u run any other applications. This is to allow this application to be the first one to catch the system shutdown event. U can, indeed, run it lastly, however, the other applications that have been running will be closed before this application can catch the system shutdown.

    The SessionEndingHandler allows you to catch the system shutdown event initiated, whether it is reboot or logoff in which u can find out in e.Reason property. Then u can cancel the system shutdown by setting e.Cancel to True.

    The Shutdown function allows you to invoke the shutdown event. set the input parameter to reboot_flag, shutdown_flag or logoff_flag. You can find the flags details in MSDN (keyword -> Win32Shutdown).

    VB Code:
    1. Dim sysevt As Microsoft.Win32.SystemEvents
    2.  
    3.     Private Sub SessionEndingHandler(ByVal sender As Object, ByVal e As SessionEndingEventArgs)
    4.             'cancel the shutdown event
    5.             e.Cancel = True            
    6.  
    7.             if e.Reason = Logoff then
    8.  
    9.                     Logofffunction
    10.                     'invoke the shutdown event
    11.                     Shutdown
    12.             elseif e.reason = shutdown then
    13.  
    14.                      shutdownfunction
    15.                     'invoke the shutdown event
    16.                     Shutdown
    17.             endif
    18.  
    19.     End Sub
    20.  
    21.     Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Load        
    22.         AddHandler sysevt.SessionEnding, AddressOf SessionEndingHandler        
    23.     End Sub
    24.  
    25.  
    26. Public Sub Shutdown(Optional ByVal pReboot As Boolean = False)
    27.         Const SHUTDOWN_FLAG As String = "1"
    28.         Const REBOOT_FLAG As String = "2"
    29.         Dim localpcname As String = System.Net.Dns.GetHostName
    30.  
    31.             Dim ms As System.Management.ManagementScope = New System.Management.ManagementScope("\\" & localpcname & "\root\cimv2")
    32.             ms.Options.EnablePrivileges = True
    33.             'Query remote computer across the connection
    34.             Dim oq As System.Management.ObjectQuery = New System.Management.ObjectQuery("SELECT * FROM Win32_OperatingSystem")
    35.             Dim query1 As System.Management.ManagementObjectSearcher = New System.Management.ManagementObjectSearcher(ms, oq)
    36.             Dim queryCollection1 As System.Management.ManagementObjectCollection = query1.Get()
    37.             Dim mo As System.Management.ManagementObject
    38.  
    39.             gFrmClient.ShutdownByServer = True
    40.             For Each mo In queryCollection1
    41.                 Dim inputparam(1) As String
    42.                 If pReboot Then
    43.                     inputparam(0) = REBOOT_FLAG
    44.                 Else
    45.                     inputparam(0) = SHUTDOWN_FLAG
    46.                 End If
    47.                 inputparam(1) = "0"
    48.                 mo.InvokeMethod("Win32Shutdown", inputparam)
    49.             Next
    50.  
    51.     End Sub

  21. #21

    Thread Starter
    Fanatic Member LITHIA's Avatar
    Join Date
    Dec 2002
    Location
    UK, England
    Posts
    575
    thanks very much, i am trying to get the code to work with my app.

    the thing i like to mention is the Shutdown sub, what is it suppost to do? I keep getting alot of errors with it, it says things like:

    Type 'System.Management.ManagementScope' is not defined

    I do have 'Imports System' in my code, but i did not see anything about Management.

    It looks like the Shutdown sub has got something to do with remote computers - i dont think i need that.

    Thanks, i am going to make my code work with my form now

  22. #22
    Member
    Join Date
    May 2003
    Posts
    58
    You just need to add System.Management.dll reference. Right click on the Reference in the Solutions Explorer and click on Add Reference...

  23. #23

    Thread Starter
    Fanatic Member LITHIA's Avatar
    Join Date
    Dec 2002
    Location
    UK, England
    Posts
    575
    hey way cool, didnt realise u cud do that. may have some fun with those references

    its good now, but how should I declare gFrmClient ?

    It isn't declared and I don't know what to declare it as to get a property like ShutdownByServer

    Thanks

    Btw, you dont have any idea how I would make the program be able to load before all the rest at startup do you? Don't worry if you don't, its not that important - I dont mind a few programs shutting down

  24. #24
    Member
    Join Date
    May 2003
    Posts
    58
    ups... just ignore/delete that line.

    Those stuff are parts of my client-server program that prevent the user on client side to shutdown the PC. That variable is just a flag to notify the SessionEndingHandler if the shutdown event is invoked by server.

    you can create a registry entry in HKEY_....../Run section so that it loads before any others. For testing stage, this would not be important. Good luck

  25. #25

    Thread Starter
    Fanatic Member LITHIA's Avatar
    Join Date
    Dec 2002
    Location
    UK, England
    Posts
    575
    thanks very much, do you know any idea how to go about that?

    thanks

  26. #26

    Thread Starter
    Fanatic Member LITHIA's Avatar
    Join Date
    Dec 2002
    Location
    UK, England
    Posts
    575
    ah man this is so fustrating...

    ive finally decided to come back to my project, but now i am having problems.

    Whenever I try to end the session while my program is up, it will prevent the computer session from ending, but it doesnt display the damn form which I ask it to.

    My code is:
    VB Code:
    1. Public Sub SessionEndingHandler(ByVal sender As Object, ByVal e As SessionEndingEventArgs)
    2.         'cancel the shutdown event
    3.         e.Cancel = True
    4.  
    5.         If e.Reason = SessionEndReasons.Logoff Then
    6.  
    7.             LogoffFunction()
    8.             Shutdown = False
    9.             Logoff = True
    10.             Dim Main As frmMain
    11.             Main.Label2.Text = "If you wish to allow the source to logoff the current user, please select Allow - otherwise select Disallow."
    12.             Main.Visible = True
    13.             Main.Show()
    14.             'invoke the shutdown event
    15.             ShutdownF()
    16.         ElseIf e.Reason = SessionEndReasons.SystemShutdown Then
    17.  
    18.             ShutdownFunction()
    19.             Logoff = False
    20.             Shutdown = True
    21.             Dim Main As frmMain
    22.             Main.Label2.Text = "If you wish to allow the source to shutdown or restart the current user, please select Allow - otherwise select Disallow."
    23.             Main.Visible = True
    24.             Main.Show()
    25.             'invoke the shutdown event
    26.             ShutdownF()
    27.         End If

    Is there any reason why the form shoudln't appear? Maybe windows is closing it as soon as it opens because of the session ending perhaps? Probably not, but is that possible?

    Thanks, this is getting really confusing now.

  27. #27
    Member
    Join Date
    May 2003
    Posts
    58
    Try this....

    Use a timer to show your form. When the sessionending is invoked, start the timer. On the first tick, stop the timer then display your form.

    See the solution attached, then you'll know
    good luck.
    Attached Files Attached Files

  28. #28

    Thread Starter
    Fanatic Member LITHIA's Avatar
    Join Date
    Dec 2002
    Location
    UK, England
    Posts
    575
    thanks, ive implemented it all in, but theres a huge problem...

    i know there is a bug in what i coded, but i have no idea where. The only way for me to find it is to debug it. But the only way to get it to display where the bug is, is to end the session.

    But when I end the session, Visual Basic asks if I want to stop debugging. Obviously if i press no, my program wont execute the code required. If I click yes, Visual Basic shuts down and ends the debug - therefor the end session carrys out.

    Using the build version, I quickly get the error displayed by the Framework, but it gets shut down so quickly i cant read it.

    Any ideas? If you want to look at my HUGE project and have a go yourself, Ill arrange a transfer.

    Thanks again

  29. #29
    Member
    Join Date
    May 2003
    Posts
    58
    what I usually did in your situation is just to put Messagebox.Show ("Iamhere" ) function at certain line. When the message appears then I know that everything is fine before that line. To be quick, I'll create several different messages at different places. You can also use it to display variable values, so you know what is happening under such situation.

    However, the good practice would be using TraceListener and log application details into log file.

    You might want to always prevent the machine to shutdown/reboot when you are testing your program by commenting out certain line(s) of code. This will make your life easier without the hassle of waiting till the machine is restarted, load the VS, start the debugging again. After you know that everything is fine then you put that code back in.

  30. #30

    Thread Starter
    Fanatic Member LITHIA's Avatar
    Join Date
    Dec 2002
    Location
    UK, England
    Posts
    575
    TraceListener sounds great, can you put it to work on a built exe?

    And if you can, how do u do it exactly, all i need to know is where this error is so i can fix it and then see if the program works overall.

    thanks

  31. #31
    Lively Member
    Join Date
    Mar 2003
    Posts
    68
    Sorry to jump in on your problem, but I'm hoping my question may be solved by your code...

    I want my application to continue running when the system logs off. Currently, it is setup as a service and that's fine, however I have made it "interactive" so that it can be modified when a user logs in. The problem is then that the application exits when the user logs-off which is not what I want (the service runs under the system account, so I don't see why it should care about the log-off).

    If I use the QueryUnload event to stop it closing when the user logs-off, it doesn't end - but the log-off doesn't happen!

    Any ideas?

  32. #32

    Thread Starter
    Fanatic Member LITHIA's Avatar
    Join Date
    Dec 2002
    Location
    UK, England
    Posts
    575
    yeah thats a bit of a problem... the idea of the code here is to stop the computer from ending the session.

    Im not sure why your service shuts itself down when you logoff, but I don't have much knowledge about services. So I don't know if they stay open or close when the session ends.

    Anyone got any ideas? I am going to have a look at that. And please don't forget about TraceListener I asked for!

  33. #33

    Thread Starter
    Fanatic Member LITHIA's Avatar
    Join Date
    Dec 2002
    Location
    UK, England
    Posts
    575
    I found this http://vbwire.com/advanced/howto/service.asp Im not sure if it will help, it looks like it only explains how to make it into a service, but if i read through it maybe it will help.

  34. #34
    Lively Member
    Join Date
    Mar 2003
    Posts
    68
    Hi LITHIA,

    Problem solved (sort-of) sorry for highjacking

  35. #35

    Thread Starter
    Fanatic Member LITHIA's Avatar
    Join Date
    Dec 2002
    Location
    UK, England
    Posts
    575
    thats fine, mind if i ask how you solved it? Just wondering if that link helped, I didn't check it myself.

  36. #36

    Thread Starter
    Fanatic Member LITHIA's Avatar
    Join Date
    Dec 2002
    Location
    UK, England
    Posts
    575
    Originally posted by LITHIA
    TraceListener sounds great, can you put it to work on a built exe?

    And if you can, how do u do it exactly, all i need to know is where this error is so i can fix it and then see if the program works overall.

    thanks
    back to prob then pls

  37. #37
    Member
    Join Date
    May 2003
    Posts
    58
    Sorry Lithia, I never used Listener class for debugging. I believe it can be used even with the released version of .exe to produce a log file. If I am not mistaken, each of the Debug.WriteLine(mMsg) will append a new line with mMsg to the log file attached to the Listener class.

    If you only want to know which line of code causes the error, putting messagebox might be enough to find out. (Use Try...Catch to find out what is the error message)
    For example:

    VB Code:
    1. Private sub Function1()
    2.     dim a as integer
    3.     dim str as string
    4.  
    5.     Try
    6.         Messagebox.show ("Entering Function1")
    7.         a = str
    8.         Messagebox.show ("Leaving Function1")
    9.     Catch ex as Exception
    10.         Messagebox.show ex.message
    11.     End try
    12. End Sub

    As result in the example above, you will see message "Entering Function1" and not "Leaving Function1". So, the error occurs after the "Entering Function1" and before "Leaving Function1".

    You can send me a copy of ur code if you want, see if i can find anything....

  38. #38
    Lively Member
    Join Date
    Mar 2003
    Posts
    68
    Nothing special, just canceled the Unload event as opposed to the QueryUnload event.

    So I guess, for your issue, you may be able to check the QueryUnload event StatusLevel and then set Cancel to True - stopped my session from logging off!

    You can look at MSDN for the form Unload & QueryUnload events for a description.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width