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:
- Go to Start -> Settings -> Control Panel -> Administrative Tools -> Services
- Open Services window
- 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();
try
{
// Get the path that stores user documents.
string myDocumentsPath =
Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
myProcess.StartInfo.FileName = myDocumentsPath + "\\MyForm.exe";
myProcess.Start();
}
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!
Regards
Tags: