I am trying to close my vb.net console app gracefully when windows shutdown occurs. I have found examples that call the Win32 function SetConsoleCtrlHandler that all basically
Pointers to functions are represented in .Net as delegates. A delegate is a kind of object and, like any other object, if there are no references to it then it will be garbage collected.
The expression (AddressOf Application_ConsoleEvent)
creates the delegate. SetConsoleCtrlHandler
is a native function, so it doesn't understand delegates; it receives a raw function pointer. So the sequence of operations is:
(AddressOf Application_ConsoleEvent)
creates the delegate.SetConsoleCtrlHandler
receives a raw function pointer that points to the delegate, and stores the raw pointer for later use.You need to declare a variable to keep a reference to the delegate. My VB is very rusty, but something like:
Shared keepAlive As ConsoleEventDelegate
Then
keepAlive = AddressOf ConsoleEventDelegate
If Not SetConsoleCtrlHandler(keepAlive, True) Then
'etc.