.

determine if a process runs as a console, windows form or service (using WMI)

using System.Management;
      
 
        private static RunAs DetermineRunAs()
        {
            int CurrentProcessId = Process.GetCurrentProcess().Id;
            uint parentid=0 ;
            string parentname;
            ManagementObjectCollection ccc = new ManagementObjectSearcher(
                string.Format("SELECT * FROM Win32_process where processid = {0}", 
                    CurrentProcessId)).Get();
            foreach (ManagementObject oReturn in ccc)
                parentid = (uint)oReturn["parentprocessid"];
            ccc = new ManagementObjectSearcher(string.Format(
                "SELECT * FROM Win32_process where processid = {0}", parentid)).Get();
            foreach (ManagementObject oReturn in ccc)
            {
                parentname = (string)oReturn["name"];
                if (parentname.ToLowerInvariant() == "services.exe")
                    return RunAs.Service;
                if (parentname.ToLowerInvariant() == "cmd.exe")
                    return RunAs.Console;
                if (parentname.ToLowerInvariant() == "explorer.exe")
                    return RunAs.Window;
            }
            return RunAs.NotSpecified;
        }
 
        static void Main(string[] args)
        {
            Configuration.RunThisAs = DetermineRunAs();
 
            switch (Configuration.RunThisAs)
            {
                case RunAs.Window:
                    Thread ProcessThread = new Thread(() => new FileExtractorThread()
                          .InstantiateAMonitorForm());
                    ProcessThread.Start();
                    while (Running)
                    {
                        Application.DoEvents();
                        if (Configuration.RunThisAs == RunAs.Service)
                            Thread.Sleep(5000);
                    }
                    break;
                case RunAs.NotSpecified:
                    break;
                case RunAs.Console:
                    break;
                case RunAs.Service:
                    System.ServiceProcess.ServiceBase.Run(new FileExtractorService());
                    break;
                default:
                    break;
            }
 
 
        }
 
 
 
    public enum RunAs
    {
        NotSpecified,
        Console,
        Window,
        Service

    }

What's your thoughts on this?

*

Protected by WP Anti Spam