Catching general window event with win32ole

I’m trying to catch the WM_QUERYENDSESSION message which is sent to
all programs when a request to shutdown Windows is made, in order to
execute some code before Windows exits.
Does anyone know how to do that in Ruby??
Is it even possible??

Regards,

Kalle

I don’t know enough about API programming to answer this with 100%
confidence, but my brief Internet research makes it sound pretty
tough. I found the following exchange in the Google group
microsoft.public.scripting.wsh. Granted, this is talking about doing
it with VBScript, but I suspect the same problem applies with Ruby:

Original question, edited for brevity:

···

I am running NT 4 SP5 with Windows Scripting Host 5.1…I believe I
should be able to detect a normal shutdown by receiving a
WM_QUERYENDSESSION message.

Responses:

  1. It isn’t. WScript/CScript as host applications certainly detect and
    respond to WM_QUERYENDSESSION but do not support any form of
    notification to a running script.

  2. It probably could be done in Visual C/C++ COM component which would
    detect the WM_QUERYENDSESSION message in its message loop and raise an
    event. But this is probably more work than you were bargaining for. I
    don’t know if it could be done as a Visual Basic COM component. In a
    regular VB application, you can “hook” the message loop and trap
    window messages such as WM_QUERYENDSESSION, but I don’t know if this
    technique applies to Active X (COM) components.

  3. To add, if you think about it, you will follow why WSH does not
    support Shutdown capturing. The interface that it has for development
    does not support creating a message queue. It has no way of receiving
    messages to a handle and passing any that it does not handle on to
    WinDefProc. You really would need to create a message queue to capture
    a “Windows Message” and then process it before finishing. Yep,
    requires creating a DLL and other mechanisms (like
    WshShell.Run(myprog, True) where myprog quits running when the End
    Session message is sent). If you have to write a DLL or EXE, may as
    well make it handle all of the rest.