R – Vista services: Can show form on invisible desktop

serviceshutdownwindows-vista

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.

Best Answer

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.

Related Topic