views:

128

answers:

1

I am attempting to show a form from a service on Vista (using .NET winforms)

Obviously the form would not show to the console user, as services are isolated in session 0.

However the experiment is to see if it is possible to "show" an invisible form and obtain a window handle & message loop

I have tried but when I issue form.Show(), only the form.Load event fires not .Shown or .FormClosing

Is there any way to capture windows messages in this way as a user application would?

I have not attempted to make the service 'interactive' as I do not wish to interact with the logged-on user.

A: 

Yes you can show a form on a service's desktop. It will not be shown to any logged in user, in fact in Vista and later OSes you cannot show it to a user even if you set the service to 'interactive'. Since the desktop is not interactive the windows messages the form receives will be slightly different but the vast majority of the events should be triggered the same in a service as they would be on an interactive desktop (I just did a quick test and got the form load, shown, activated and closing events).

One thing to remember is that in order to show a form your thread must be an STA thread and a message loop must be created, either by calling ShowDialog or Applicaton.Run. Also, remember all external interaction with the form will need to be marshaled to the correct thread using Invoke or BeginInvoke on the form instance.

This is certainly very doable but is really not recommended at all. You must be absolutely sure that the form and any components it contains will not show any unexpected UI, such as a message box, under any circumstances. The only time this method can really be justified is when you are working with a dubious quality legacy or 3rd party tool that requires handle creation in order to function properly.

Stephen Martin
Many thanks. How did you start the form in your test?I tried ShowDialog() but got >>'System.InvalidOperationException' Showing a modal dialog box or form when the application is not running in UserInteractive mode is not a valid operation. Specify the ServiceNotification or DefaultDesktopOnly style to display a notification from a service application.<<I want to display this (hidden) window and obtain messages in attempt to handle WM_QUERYENDSESSION in the service when the system is shutting down - in an attempt to cancel shutdown in conjunction with ShutdownBlockReasonCreate
Jeff Parker
I used Application.Run in my test and that works fine. ShowDialog used to work fine but apparently they added a check in the 2.0 framework to disallow it. Personally, I think canceling shutdown from a service is not a very good idea but if you really want to do that it should work. Just call Application.Run(myFormInstance) instead of myFormInstance.ShowDialog.
Stephen Martin