Aug 1 2007

Windows Forms inside Windows Service

Category:Bil@l @ 12:28

In a windows service that I was creating, I needed to show a Windows Form at some point and that was not working since the Windows Service operates on a background thread other than the one handling the desktop applications.

So the way to go in order to allow Windows Forms inside a Windows Service is to follow these steps:

  1. Go to Start -> Settings -> Control Panel -> Administrative Tools -> Services
  2. Open Services window
  3. Locate your running service, right click, click on the Logon Tab, then select checkbox (Allow service to interact with Desktop).

Now to fire a Windows Form inside your Windows Service, here is the code:

 Process myProcess = new Process();

            // Get the path that stores user documents.
            string myDocumentsPath =

            myProcess.StartInfo.FileName = myDocumentsPath + "\\MyForm.exe";
        catch (Win32Exception ex)
            if (ex.NativeErrorCode == ERROR_FILE_NOT_FOUND)
                Console.WriteLine(ex.Message + ". Check the path.");

            else if (ex.NativeErrorCode == ERROR_ACCESS_DENIED)
                Console.WriteLine(ex.Message +
                    ". You do not have permission to access this file.");

Make sure to include those two constants:

        const int ERROR_FILE_NOT_FOUND =2;
        const int ERROR_ACCESS_DENIED = 5;

Also add reference to the following namespaces:

using System.Diagnostics;
using System.ComponentModel;


Hope this posts helped you up!




Comments are closed