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.
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.
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.
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
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
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.
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.
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.
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>
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.
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.
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:
Dim sysevt As Microsoft.Win32.SystemEvents
Private Sub SessionEndingHandler(ByVal sender As Object, ByVal e As SessionEndingEventArgs)
'cancel the shutdown event
e.Cancel = True
if e.Reason = Logoff then
Logofffunction
'invoke the shutdown event
Shutdown
elseif e.reason = shutdown then
shutdownfunction
'invoke the shutdown event
Shutdown
endif
End Sub
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Load
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
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
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:
Public Sub SessionEndingHandler(ByVal sender As Object, ByVal e As SessionEndingEventArgs)
'cancel the shutdown event
e.Cancel = True
If e.Reason = SessionEndReasons.Logoff Then
LogoffFunction()
Shutdown = False
Logoff = True
Dim Main As frmMain
Main.Label2.Text = "If you wish to allow the source to logoff the current user, please select Allow - otherwise select Disallow."
Main.Visible = True
Main.Show()
'invoke the shutdown event
ShutdownF()
ElseIf e.Reason = SessionEndReasons.SystemShutdown Then
ShutdownFunction()
Logoff = False
Shutdown = True
Dim Main As frmMain
Main.Label2.Text = "If you wish to allow the source to shutdown or restart the current user, please select Allow - otherwise select Disallow."
Main.Visible = True
Main.Show()
'invoke the shutdown event
ShutdownF()
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, 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.
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.
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!
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!
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.
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:
Private sub Function1()
dim a as integer
dim str as string
Try
Messagebox.show ("Entering Function1")
a = str
Messagebox.show ("Leaving Function1")
Catch ex as Exception
Messagebox.show ex.message
End try
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....
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.