C# windows服务程序开机自启动exe程序

发布时间:2024年01月03日
我们使用传统的Process.Start(".exe")启动进程会遇到无法打开UI界面的问题,尤其是我们需要进行开启自启动程序设置时出现诸多问题,于是我们就想到采用windows服务开机自启动来创建启动一个新的exe程序,并且是显式运行。

首先是打开Visual Studio创建一个windos服务程序

详细创建windos服务程序不过多赘述,在另外一篇文章里有介绍【Visual Studio C#创建windows服务程序-CSDN博客

我们在OnStart方法中写下我们启动程序的执行逻辑,具体代码如下

using System;
using System.ServiceProcess;
using System.Threading.Tasks;
using System.Configuration;
using log4net;
using System.Diagnostics;
using System.IO;
using System.Threading;
using System.Linq;

namespace Web.Server.Api
{
    public partial class MyService : ServiceBase
    {
        public MyService()
        {
            logger = LogManager.GetLogger(typeof(MyService));
            path = @"D:\bin\Release\MCS.exe";
            InitializeComponent();
        }
        private readonly string path;
        private readonly ILog logger;
        /// <summary>
        /// 服务启动时执行的操作
        /// </summary>
        /// <param name="args"></param>
        protected override void OnStart(string[] args)
        {
            Task.Run(() => {
                for (int i = 0; i < 20; i++) //为了防止启动失败,我们这里设置了一个循环,默认程序执行20次
                {
                    try
                    {
                        string processName = Path.GetFileNameWithoutExtension(path); //获取应用程序名称
                        var processes = Process.GetProcesses(); //获取所有进程
                        if (processes.Any(v => v.ProcessName.Equals(processName, StringComparison.OrdinalIgnoreCase)))
                        {
                            logger.Info($"此程序已正常启动 {processName}\n路径:{path}");
                            break; //程序启动成功,退出for循环
                        }
                        else
                        {
                            this.Start(path);
                        }
                    }
                    catch (Exception err)
                    {
                        logger.Error(err.Message, err);
                    }
                    finally
                    {
                        Thread.Sleep(1000);
                    }
                }
            });
        }
        protected override void OnStop()
        {
            string processName = Process.GetCurrentProcess().ProcessName;
            logger.Info($"服务管理程序已退出 {processName}");
            base.OnStop();
        }

        /// <summary>
        /// 启动方法1
        /// </summary>
        /// <param name="appStartPath"></param>
        private void Start(string appStartPath)
        {
            try
            {
                UserProcess.PROCESS_INFORMATION pInfo = new UserProcess.PROCESS_INFORMATION();
                UserProcess.StartProcessAndBypassUAC(appStartPath, string.Empty, out pInfo);
            }
            catch (Exception err)
            {
                logger.Error(err.Message, err);
            }
        }

        /// <summary>
        /// 启动方法2
        /// </summary>
        /// <param name="appStartPath"></param>
        private void Start2(string appStartPath)
        {
            try
            {
                IntPtr userTokenHandle = IntPtr.Zero;
                ApiDefinitions.WTSQueryUserToken(ApiDefinitions.WTSGetActiveConsoleSessionId(), ref userTokenHandle);
                ApiDefinitions.PROCESS_INFORMATION procInfo = new ApiDefinitions.PROCESS_INFORMATION();
                ApiDefinitions.STARTUPINFO startInfo = new ApiDefinitions.STARTUPINFO();
                startInfo.cb = (uint)System.Runtime.InteropServices.Marshal.SizeOf(startInfo);
                ApiDefinitions.CreateProcessAsUser(userTokenHandle, appStartPath, string.Empty, IntPtr.Zero, IntPtr.Zero, false, 0, IntPtr.Zero, null, ref startInfo, out procInfo);
                if (userTokenHandle != IntPtr.Zero)
                {
                    ApiDefinitions.CloseHandle(userTokenHandle);
                }
                int _currentAquariusProcessId = (int)procInfo.dwProcessId;
            }
            catch (Exception err)
            {
                logger.Error(err.Message, err);
            }
        }
    }
}

上述代码中我们给出了两种启动方式,两种启动方式的代码大同小异,推荐第一种方法,比较简洁。两种启动方式的具体代码如下:

启动方法1:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Security;
using System.Text;
using System.Threading.Tasks;

namespace Web.Server.Api
{
    public class UserProcess
    {
        #region Structures
        [StructLayout(LayoutKind.Sequential)]
        public struct SECURITY_ATTRIBUTES
        {
            public int Length;
            public IntPtr lpSecurityDescriptor;
            public bool bInheritHandle;
        }
        [StructLayout(LayoutKind.Sequential)]
        public struct STARTUPINFO
        {
            public int cb;
            public String lpReserved;
            public String lpDesktop;
            public String lpTitle;
            public uint dwX;
            public uint dwY;
            public uint dwXSize;
            public uint dwYSize;
            public uint dwXCountChars;
            public uint dwYCountChars;
            public uint dwFillAttribute;
            public uint dwFlags;
            public short wShowWindow;
            public short cbReserved2;
            public IntPtr lpReserved2;
            public IntPtr hStdInput;
            public IntPtr hStdOutput;
            public IntPtr hStdError;
        }
        [StructLayout(LayoutKind.Sequential)]
        public struct PROCESS_INFORMATION
        {
            public IntPtr hProcess;
            public IntPtr hThread;
            public uint dwProcessId;
            public uint dwThreadId;
        }
        #endregion
        #region Enumerations
        enum TOKEN_TYPE : int
        {
            TokenPrimary = 1,
            TokenImpersonation = 2
        }
        enum SECURITY_IMPERSONATION_LEVEL : int
        {
            SecurityAnonymous = 0,
            SecurityIdentification = 1,
            SecurityImpersonation = 2,
            SecurityDelegation = 3,
        }
        enum WTSInfoClass
        {
            InitialProgram,
            ApplicationName,
            WorkingDirectory,
            OEMId,
            SessionId,
            UserName,
            WinStationName,
            DomainName,
            ConnectState,
            ClientBuildNumber,
            ClientName,
            ClientDirectory,
            ClientProductId,
            ClientHardwareId,
            ClientAddress,
            ClientDisplay,
            ClientProtocolType
        }
        #endregion
        #region Constants
        public const int TOKEN_DUPLICATE = 0x0002;
        public const uint MAXIMUM_ALLOWED = 0x2000000;
        public const int CREATE_NEW_CONSOLE = 0x00000010;
        public const int IDLE_PRIORITY_CLASS = 0x40;
        public const int NORMAL_PRIORITY_CLASS = 0x20;
        public const int HIGH_PRIORITY_CLASS = 0x80;
        public const int REALTIME_PRIORITY_CLASS = 0x100;
        #endregion
        #region Win32 API Imports
        [DllImport("kernel32.dll", SetLastError = true)]
        private static extern bool CloseHandle(IntPtr hSnapshot);
        [DllImport("kernel32.dll")]
        static extern uint WTSGetActiveConsoleSessionId();
        [DllImport("wtsapi32.dll", CharSet = CharSet.Unicode, SetLastError = true), SuppressUnmanagedCodeSecurityAttribute]
        static extern bool WTSQuerySessionInformation(System.IntPtr hServer, int sessionId, WTSInfoClass wtsInfoClass, out System.IntPtr ppBuffer, out uint pBytesReturned);
        [DllImport("advapi32.dll", EntryPoint = "CreateProcessAsUser", SetLastError = true, CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)]
        public extern static bool CreateProcessAsUser(IntPtr hToken, String lpApplicationName, String lpCommandLine, ref SECURITY_ATTRIBUTES lpProcessAttributes,
            ref SECURITY_ATTRIBUTES lpThreadAttributes, bool bInheritHandle, int dwCreationFlags, IntPtr lpEnvironment,
            String lpCurrentDirectory, ref STARTUPINFO lpStartupInfo, out PROCESS_INFORMATION lpProcessInformation);
        [DllImport("kernel32.dll")]
        static extern bool ProcessIdToSessionId(uint dwProcessId, ref uint pSessionId);
        [DllImport("advapi32.dll", EntryPoint = "DuplicateTokenEx")]
        public extern static bool DuplicateTokenEx(IntPtr ExistingTokenHandle, uint dwDesiredAccess,
            ref SECURITY_ATTRIBUTES lpThreadAttributes, int TokenType,
            int ImpersonationLevel, ref IntPtr DuplicateTokenHandle);
        [DllImport("kernel32.dll")]
        static extern IntPtr OpenProcess(uint dwDesiredAccess, bool bInheritHandle, uint dwProcessId);
        [DllImport("advapi32", SetLastError = true), SuppressUnmanagedCodeSecurityAttribute]
        static extern bool OpenProcessToken(IntPtr ProcessHandle, int DesiredAccess, ref IntPtr TokenHandle);
        #endregion
        public static string GetCurrentActiveUser()
        {
            IntPtr hServer = IntPtr.Zero, state = IntPtr.Zero;
            uint bCount = 0;
            // obtain the currently active session id; every logged on user in the system has a unique session id  
            uint dwSessionId = WTSGetActiveConsoleSessionId();
            string domain = string.Empty, userName = string.Empty;
            if (WTSQuerySessionInformation(hServer, (int)dwSessionId, WTSInfoClass.DomainName, out state, out bCount))
            {
                domain = Marshal.PtrToStringAuto(state);
            }
            if (WTSQuerySessionInformation(hServer, (int)dwSessionId, WTSInfoClass.UserName, out state, out bCount))
            {
                userName = Marshal.PtrToStringAuto(state);
            }
            return string.Format("{0}\\{1}", domain, userName);
        }
        /// <summary>  
        /// Launches the given application with full admin rights, and in addition bypasses the Vista UAC prompt  
        /// </summary>  
        /// <param name="applicationName">The name of the application to launch</param>  
        /// <param name="procInfo">Process information regarding the launched application that gets returned to the caller</param>  
        /// <returns></returns>  
        public static bool StartProcessAndBypassUAC(String applicationName, String command, out PROCESS_INFORMATION procInfo)
        {
            uint winlogonPid = 0;
            IntPtr hUserTokenDup = IntPtr.Zero, hPToken = IntPtr.Zero, hProcess = IntPtr.Zero;
            procInfo = new PROCESS_INFORMATION();
            // obtain the currently active session id; every logged on user in the system has a unique session id  
            uint dwSessionId = WTSGetActiveConsoleSessionId();
            // obtain the process id of the winlogon process that is running within the currently active session  
            System.Diagnostics.Process[] processes = System.Diagnostics.Process.GetProcessesByName("winlogon");
            foreach (System.Diagnostics.Process p in processes)
            {
                if ((uint)p.SessionId == dwSessionId)
                {
                    winlogonPid = (uint)p.Id;
                }
            }
            // obtain a handle to the winlogon process  
            hProcess = OpenProcess(MAXIMUM_ALLOWED, false, winlogonPid);
            // obtain a handle to the access token of the winlogon process  
            if (!OpenProcessToken(hProcess, TOKEN_DUPLICATE, ref hPToken))
            {
                CloseHandle(hProcess);
                return false;
            }
            // Security attibute structure used in DuplicateTokenEx and CreateProcessAsUser  
            // I would prefer to not have to use a security attribute variable and to just   
            // simply pass null and inherit (by default) the security attributes  
            // of the existing token. However, in C# structures are value types and therefore  
            // cannot be assigned the null value.  
            SECURITY_ATTRIBUTES sa = new SECURITY_ATTRIBUTES();
            sa.Length = Marshal.SizeOf(sa);
            // copy the access token of the winlogon process; the newly created token will be a primary token  
            if (!DuplicateTokenEx(hPToken, MAXIMUM_ALLOWED, ref sa, (int)SECURITY_IMPERSONATION_LEVEL.SecurityIdentification, (int)TOKEN_TYPE.TokenPrimary, ref hUserTokenDup))
            {
                CloseHandle(hProcess);
                CloseHandle(hPToken);
                return false;
            }
            // By default CreateProcessAsUser creates a process on a non-interactive window station, meaning  
            // the window station has a desktop that is invisible and the process is incapable of receiving  
            // user input. To remedy this we set the lpDesktop parameter to indicate we want to enable user   
            // interaction with the new process.  
            STARTUPINFO si = new STARTUPINFO();
            si.cb = (int)Marshal.SizeOf(si);
            si.lpDesktop = @"winsta0\default"; // interactive window station parameter; basically this indicates that the process created can display a GUI on the desktop  
            // flags that specify the priority and creation method of the process  
            int dwCreationFlags = NORMAL_PRIORITY_CLASS | CREATE_NEW_CONSOLE;
            // create a new process in the current user's logon session  
            bool result = CreateProcessAsUser(hUserTokenDup,        // client's access token  
                                            applicationName,        // file to execute  
                                            command,                // command line  
                                            ref sa,                 // pointer to process SECURITY_ATTRIBUTES  
                                            ref sa,                 // pointer to thread SECURITY_ATTRIBUTES  
                                            false,                  // handles are not inheritable  
                                            dwCreationFlags,        // creation flags  
                                            IntPtr.Zero,            // pointer to new environment block   
                                            null,                   // name of current directory   
                                            ref si,                 // pointer to STARTUPINFO structure  
                                            out procInfo            // receives information about new process  
                                            );
            // invalidate the handles  
            CloseHandle(hProcess);
            CloseHandle(hPToken);
            CloseHandle(hUserTokenDup);
            return result; // return the result  
        }
    }
}

启动方法2:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.ConstrainedExecution;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace Web.Server.Api
{
    public class ApiDefinitions
    {
        public struct WTS_SESSION_INFO
        {
            public uint SessionId;

            [MarshalAs(UnmanagedType.LPTStr)]
            public string pWinStationName;

            public WTS_CONNECTSTATE_CLASS State;
        }

        public enum WTS_CONNECTSTATE_CLASS
        {
            WTSActive,
            WTSConnected,
            WTSConnectQuery,
            WTSShadow,
            WTSDisconnected,
            WTSIdle,
            WTSListen,
            WTSReset,
            WTSDown,
            WTSInit
        }

        public enum WTS_INFO_CLASS
        {
            WTSInitialProgram,
            WTSApplicationName,
            WTSWorkingDirectory,
            WTSOEMId,
            WTSSessionId,
            WTSUserName,
            WTSWinStationName,
            WTSDomainName,
            WTSConnectState,
            WTSClientBuildNumber,
            WTSClientName,
            WTSClientDirectory,
            WTSClientProductId,
            WTSClientHardwareId,
            WTSClientAddress,
            WTSClientDisplay,
            WTSClientProtocolType,
            WTSIdleTime,
            WTSLogonTime,
            WTSIncomingBytes,
            WTSOutgoingBytes,
            WTSIncomingFrames,
            WTSOutgoingFrames,
            WTSClientInfo,
            WTSSessionInfo,
            WTSSessionInfoEx,
            WTSConfigInfo,
            WTSValidationInfo,
            WTSSessionAddressV4,
            WTSIsRemoteSession
        }

        public class LOGON_RIGHT
        {
            public const string SE_BATCH_LOGON_NAME = "SeBatchLogonRight";

            public const string SE_SERVICE_LOGON_NAME = "SeServiceLogonRight";

            public const string SE_DENY_BATCH_LOGON_NAME = "SeDenyBatchLogonRight";

            public const string SE_DENY_INTERACTIVE_LOGON_NAME = "SeDenyInteractiveLogonRight";

            public const string SE_DENY_NETWORK_LOGON_NAME = "SeDenyNetworkLogonRight";

            public const string SE_DENY_REMOTE_INTERACTIVE_LOGON_NAME = "SeDenyRemoteInteractiveLogonRight";

            public const string SE_DENY_SERVICE_LOGON_NAME = "SeDenyServiceLogonRight";

            public const string SE_INTERACTIVE_LOGON_NAME = "SeInteractiveLogonRight";

            public const string SE_NETWORK_LOGON_NAME = "SeNetworkLogonRight";

            public const string SE_REMOTE_INTERACTIVE_LOGON_NAME = "SeRemoteInteractiveLogonRight";
        }

        public enum LSA_POLICY_ACCESS_MASK : uint
        {
            POLICY_VIEW_LOCAL_INFORMATION = 1u,
            POLICY_VIEW_AUDIT_INFORMATION = 2u,
            POLICY_GET_PRIVATE_INFORMATION = 4u,
            POLICY_TRUST_ADMIN = 8u,
            POLICY_CREATE_ACCOUNT = 0x10u,
            POLICY_CREATE_SECRET = 0x20u,
            POLICY_CREATE_PRIVILEGE = 0x40u,
            POLICY_SET_DEFAULT_QUOTA_LIMITS = 0x80u,
            POLICY_SET_AUDIT_REQUIREMENTS = 0x100u,
            POLICY_AUDIT_LOG_ADMIN = 0x200u,
            POLICY_SERVER_ADMIN = 0x400u,
            POLICY_LOOKUP_NAMES = 0x800u,
            POLICY_NOTIFICATION = 0x1000u
        }

        public enum SERVICE_STATES : uint
        {
            SERVICE_CONTINUE_PENDING = 5u,
            SERVICE_PAUSE_PENDING = 6u,
            SERVICE_PAUSED = 7u,
            SERVICE_RUNNING = 4u,
            SERVICE_START_PENDING = 2u,
            SERVICE_STOP_PENDING = 3u,
            SERVICE_STOPPED = 1u
        }

        public enum SERVICE_CONTROL_CODES : uint
        {
            SERVICE_CONTROL_CONTINUE = 3u,
            SERVICE_CONTROL_INTERROGATE = 4u,
            SERVICE_CONTROL_NETBINDADD = 7u,
            SERVICE_CONTROL_NETBINDDISABLE = 10u,
            SERVICE_CONTROL_NETBINDENABLE = 9u,
            SERVICE_CONTROL_NETBINDREMOVE = 8u,
            SERVICE_CONTROL_PARAMCHANGE = 6u,
            SERVICE_CONTROL_PAUSE = 2u,
            SERVICE_CONTROL_STOP = 1u
        }

        [StructLayout(LayoutKind.Sequential)]
        public class QUERY_SERVICE_CONFIG
        {
            public uint dwServiceType;

            public uint dwStartType;

            public uint dwErrorControl;

            [MarshalAs(UnmanagedType.LPWStr)]
            public string lpBinaryPathName;

            [MarshalAs(UnmanagedType.LPWStr)]
            public string lpLoadOrderGroup;

            public uint dwTagId;

            public IntPtr lpDependencies;

            [MarshalAs(UnmanagedType.LPWStr)]
            public string lpServiceStartName;

            [MarshalAs(UnmanagedType.LPWStr)]
            public string lpDisplayName;
        }

        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
        public struct SHARE_INFO_1
        {
            [MarshalAs(UnmanagedType.LPWStr)]
            public string shi1_netname;

            public ShareType shi1_type;

            [MarshalAs(UnmanagedType.LPWStr)]
            public string shi1_remark;
        }

        public enum ShareType
        {
            STYPE_DISKTREE = 0,
            STYPE_PRINTQ = 1,
            STYPE_DEVICE = 2,
            STYPE_IPC = 3,
            STYPE_TEMPORARY = 0x40000000,
            STYPE_SPECIAL = int.MinValue
        }

        [Flags]
        public enum DsGetDcNameFlags
        {
            DS_FORCE_REDISCOVERY = 0x1,
            DS_DIRECTORY_SERVICE_REQUIRED = 0x10,
            DS_DIRECTORY_SERVICE_PREFERRED = 0x20,
            DS_GC_SERVER_REQUIRED = 0x40,
            DS_PDC_REQUIRED = 0x80,
            DS_BACKGROUND_ONLY = 0x100,
            DS_IP_REQUIRED = 0x200,
            DS_KDC_REQUIRED = 0x400,
            DS_TIMESERV_REQUIRED = 0x800,
            DS_WRITABLE_REQUIRED = 0x1000,
            DS_GOOD_TIMESERV_PREFERRED = 0x2000,
            DS_AVOID_SELF = 0x4000,
            DS_ONLY_LDAP_NEEDED = 0x8000,
            DS_IS_FLAT_NAME = 0x10000,
            DS_IS_DNS_NAME = 0x20000,
            DS_TRY_NEXTCLOSEST_SITE = 0x40000,
            DS_DIRECTORY_SERVICE_6_REQUIRED = 0x80000,
            DS_WEB_SERVICE_REQUIRED = 0x100000,
            DS_RETURN_DNS_NAME = 0x40000000,
            DS_RETURN_FLAT_NAME = int.MinValue
        }

        public enum SID_NAME_USE
        {
            SidTypeUser = 1,
            SidTypeGroup,
            SidTypeDomain,
            SidTypeAlias,
            SidTypeWellKnownGroup,
            SidTypeDeletedAccount,
            SidTypeInvalid,
            SidTypeUnknown,
            SidTypeComputer,
            SidTypeLabel
        }

        public struct STARTUPINFO
        {
            public uint cb;

            [MarshalAs(UnmanagedType.LPWStr)]
            public string lpReserved;

            [MarshalAs(UnmanagedType.LPWStr)]
            public string lpDesktop;

            [MarshalAs(UnmanagedType.LPWStr)]
            public string lpTitle;

            public uint dwX;

            public uint dwY;

            public uint dwXSize;

            public uint dwYSize;

            public uint dwXCountChars;

            public uint dwYCountChars;

            public uint dwFillAttribute;

            public uint dwFlags;

            public ushort wShowWindow;

            public ushort cbReserved2;

            public IntPtr lpReserved2;

            public IntPtr hStdInput;

            public IntPtr hStdOutput;

            public IntPtr hStdError;
        }

        public struct PROCESS_INFORMATION
        {
            public IntPtr hProcess;

            public IntPtr hThread;

            public uint dwProcessId;

            public uint dwThreadId;
        }

        public struct IP_INTERFACE_INFO
        {
            public int NumAdapters;

            public IP_ADAPTER_INDEX_MAP[] Adapter;
        }

        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
        public struct IP_ADAPTER_INDEX_MAP
        {
            public int Index;

            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
            public string Name;
        }

        public enum NET_API_STATUS
        {
            NERR_SUCCESS = 0,
            ERROR_ACCESS_DENIED = 5,
            PATH_NOT_FOUND = 53,
            ERROR_INVALID_PARAMETER = 87,
            ERROR_INVALID_NAME = 123,
            ERROR_INVALID_LEVEL = 124,
            ERROR_MORE_DATA = 234,
            ERROR_NO_SUCH_DOMAIN = 1355,
            NERR_UNKNOWNDEVDIR = 2116,
            NERR_REDIRECTEDPATH = 2117,
            NERR_DUPLICATESHARE = 2118,
            NERR_BUFTOOSMALL = 2123,
            NERR_ACCT_EXISTS = 2224,
            NERR_SETUPNOTJOINED = 2692
        }

        public struct SHARE_INFO_502
        {
            [MarshalAs(UnmanagedType.LPWStr)]
            public string shi502_netname;

            public uint shi502_type;

            [MarshalAs(UnmanagedType.LPWStr)]
            public string shi502_remark;

            public int shi502_permissions;

            public int shi502_max_uses;

            public int shi502_current_uses;

            [MarshalAs(UnmanagedType.LPWStr)]
            public string shi502_path;

            [MarshalAs(UnmanagedType.LPWStr)]
            public string shi502_passwd;

            public int shi502_reserved;

            public IntPtr shi502_security_descriptor;
        }

        public struct SECURITY_DESCRIPTOR
        {
            public byte Revision;

            public byte Sbz1;

            public ushort Control;

            public IntPtr Owner;

            public IntPtr Group;

            public IntPtr Sacl;

            public IntPtr Dacl;
        }

        public enum ACCESS_MASK : uint
        {
            DELETE = 0x10000u,
            READ_CONTROL = 0x20000u,
            WRITE_DAC = 0x40000u,
            WRITE_OWNER = 0x80000u,
            SYNCHRONIZE = 0x100000u,
            STANDARD_RIGHTS_REQUIRED = 983040u,
            STANDARD_RIGHTS_READ = 0x20000u,
            GENERIC_ALL = 0x10000000u,
            GENERIC_READ = 0x80000000u,
            GENERIC_WRITE = 0x40000000u,
            GENERIC_EXECUTE = 0x20000000u,
            CHANGE = 1245631u
        }

        public enum ACCESS_MODE : uint
        {
            NOT_USED_ACCESS,
            GRANT_ACCESS,
            SET_ACCESS,
            DENY_ACCESS,
            REVOKE_ACCESS,
            SET_AUDIT_SUCCESS,
            SET_AUDIT_FAILURE
        }

        public enum MULTIPLE_TRUSTEE_OPERATION : uint
        {
            NO_MULTIPLE_TRUSTEE,
            TRUSTEE_IS_IMPERSONATE
        }

        public enum TRUSTEE_FORM : uint
        {
            TRUSTEE_IS_SID,
            TRUSTEE_IS_NAME,
            TRUSTEE_BAD_FORM,
            TRUSTEE_IS_OBJECTS_AND_SID,
            TRUSTEE_IS_OBJECTS_AND_NAME
        }

        public enum TRUSTEE_TYPE : uint
        {
            TRUSTEE_IS_UNKNOWN,
            TRUSTEE_IS_USER,
            TRUSTEE_IS_GROUP,
            TRUSTEE_IS_DOMAIN,
            TRUSTEE_IS_ALIAS,
            TRUSTEE_IS_WELL_KNOWN_GROUP,
            TRUSTEE_IS_DELETED,
            TRUSTEE_IS_INVALID,
            TRUSTEE_IS_COMPUTER
        }

        public enum SYSTEM_POWER_STATE
        {
            PowerSystemUnspecified,
            PowerSystemWorking,
            PowerSystemSleeping1,
            PowerSystemSleeping2,
            PowerSystemSleeping3,
            PowerSystemHibernate,
            PowerSystemShutdown,
            PowerSystemMaximum
        }

        public enum POWER_ACTION
        {
            PowerActionNone,
            PowerActionReserved,
            PowerActionSleep,
            PowerActionHibernate,
            PowerActionShutdown,
            PowerActionShutdownReset,
            PowerActionShutdownOff,
            PowerActionWarmEject
        }

        public struct EXPLICIT_ACCESS
        {
            public uint grfAccessPermissions;

            public ACCESS_MODE grfAccessMode;

            public uint grfInheritance;

            public TRUSTEE Trustee;
        }

        public struct TRUSTEE
        {
            public uint pMultipleTrustee;

            public MULTIPLE_TRUSTEE_OPERATION MultipleTrusteeOperation;

            public TRUSTEE_FORM TrusteeForm;

            public TRUSTEE_TYPE TrusteeType;

            [MarshalAs(UnmanagedType.LPTStr)]
            public string ptstrName;
        }

        public struct SHARE_INFO_2
        {
            [MarshalAs(UnmanagedType.LPWStr)]
            public string shi2_netname;

            public uint shi2_type;

            [MarshalAs(UnmanagedType.LPWStr)]
            public string shi2_remark;

            public uint shi2_permissions;

            public int shi2_max_uses;

            public uint shi2_current_uses;

            [MarshalAs(UnmanagedType.LPWStr)]
            public string shi2_path;

            [MarshalAs(UnmanagedType.LPWStr)]
            public string shi2_passwd;
        }

        public struct SP_DEVINFO_DATA
        {
            public uint cbSize;

            public Guid ClassGuid;

            public uint DevInst;

            public IntPtr Reserved;
        }

        [StructLayout(LayoutKind.Sequential, Pack = 1)]
        public struct Process_Basic_Information
        {
            public IntPtr ExitStatus;

            public IntPtr PebBaseAddress;

            public IntPtr AffinityMask;

            public IntPtr BasePriority;

            public IntPtr UniqueProcessID;

            public IntPtr InheritedFromUniqueProcessId;
        }

        public struct HIGHCONTRAST
        {
            public uint cbSize;

            public uint dwFlags;

            [MarshalAs(UnmanagedType.LPWStr)]
            public string lpszDefaultScheme;
        }

        public struct NETRESOURCE
        {
            public uint dwScope;

            public uint dwType;

            public uint dwDisplayType;

            public uint dwUsage;

            [MarshalAs(UnmanagedType.LPWStr)]
            public string lpLocalName;

            [MarshalAs(UnmanagedType.LPWStr)]
            public string lpRemoteName;

            [MarshalAs(UnmanagedType.LPWStr)]
            public string lpComment;

            [MarshalAs(UnmanagedType.LPWStr)]
            public string lpProvider;
        }

        public struct ENUM_SERVICE_STATUS_PROCESS
        {
            [MarshalAs(UnmanagedType.LPTStr)]
            public string lpServiceName;

            [MarshalAs(UnmanagedType.LPTStr)]
            public string lpDisplayName;

            public SERVICE_STATUS_PROCESS ServiceStatusProcess;
        }

        public struct SERVICE_STATUS_PROCESS
        {
            public uint dwServiceType;

            public SERVICE_STATES dwCurrentState;

            public uint dwControlsAccepted;

            public uint dwWin32ExitCode;

            public uint dwServiceSpecificExitCode;

            public uint dwCheckPoint;

            public uint dwWaitHint;

            public uint dwProcessId;

            public uint dwServiceFlags;
        }

        public struct FLASHWINFO
        {
            public uint cbSize;

            public IntPtr hwnd;

            public uint dwFlags;

            public uint uCount;

            public uint dwTimeout;
        }

        public struct POWER_POLICY
        {
            public USER_POWER_POLICY user;

            public MACHINE_POWER_POLICY mach;
        }

        public struct MACHINE_POWER_POLICY
        {
            public uint Revision;

            public SYSTEM_POWER_STATE MinSleepAc;

            public SYSTEM_POWER_STATE MinSleepDc;

            public SYSTEM_POWER_STATE ReducedLatencySleepAc;

            public SYSTEM_POWER_STATE ReducedLatencySleepDc;

            public uint DozeTimeoutAc;

            public uint DozeTimeoutDc;

            public uint DozeS4TimeoutAc;

            public uint DozeS4TimeoutDc;

            public byte MinThrottleAc;

            public byte MinThrottleDc;

            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 2)]
            public string pad1;

            public POWER_ACTION_POLICY OverThrottledAc;

            public POWER_ACTION_POLICY OverThrottledDc;
        }

        public struct USER_POWER_POLICY
        {
            public uint Revision;

            public POWER_ACTION_POLICY IdleAc;

            public POWER_ACTION_POLICY IdleDc;

            public uint IdleTimeoutAc;

            public uint IdleTimeoutDc;

            public byte IdleSensitivityAc;

            public byte IdleSensitivityDc;

            public byte ThrottlePolicyAc;

            public byte ThrottlePolicyDc;

            public SYSTEM_POWER_STATE MaxSleepAc;

            public SYSTEM_POWER_STATE MaxSleepDc;

            [MarshalAs(UnmanagedType.ByValArray, SizeConst = 2, ArraySubType = UnmanagedType.U4)]
            public uint[] Reserved;

            public uint VideoTimeoutAc;

            public uint VideoTimeoutDc;

            public uint SpindownTimeoutAc;

            public uint SpindownTimeoutDc;

            public byte OptimizeForPowerAc;

            public byte OptimizeForPowerDc;

            public byte FanThrottleToleranceAc;

            public byte FanThrottleToleranceDc;

            public byte ForcedThrottleAc;

            public byte ForcedThrottleDc;
        }

        public struct POWER_ACTION_POLICY
        {
            public POWER_ACTION Action;

            public uint Flags;

            public uint EventCode;
        }

        public struct GLOBAL_POWER_POLICY
        {
            public GLOBAL_USER_POWER_POLICY user;

            public GLOBAL_MACHINE_POWER_POLICY mach;
        }

        public struct GLOBAL_USER_POWER_POLICY
        {
            public uint Revision;

            public POWER_ACTION_POLICY PowerButtonAc;

            public POWER_ACTION_POLICY PowerButtonDc;

            public POWER_ACTION_POLICY SleepButtonAc;

            public POWER_ACTION_POLICY SleepButtonDc;

            public POWER_ACTION_POLICY LidCloseAc;

            public POWER_ACTION_POLICY LidCloseDc;

            [MarshalAs(UnmanagedType.ByValArray, SizeConst = 4, ArraySubType = UnmanagedType.Struct)]
            public SYSTEM_POWER_LEVEL[] DischargePolicy;

            public uint GlobalFlags;
        }

        public struct GLOBAL_MACHINE_POWER_POLICY
        {
            public uint Revision;

            public SYSTEM_POWER_STATE LidOpenWakeAc;

            public SYSTEM_POWER_STATE LidOpenWakeDc;

            public uint BroadcastCapacityResolution;
        }

        public struct SYSTEM_POWER_LEVEL
        {
            public byte Enable;

            [MarshalAs(UnmanagedType.ByValArray, SizeConst = 3, ArraySubType = UnmanagedType.I1)]
            public byte[] Spare;

            public uint BatteryLevel;

            public POWER_ACTION_POLICY PowerPolicy;

            public SYSTEM_POWER_STATE MinSystemState;
        }

        [StructLayout(LayoutKind.Sequential, Pack = 4)]
        public struct SHQUERYRBINFO
        {
            public uint cbSize;

            public ulong i64Size;

            public ulong i64NumItems;
        }

        public struct RECT
        {
            public int left;

            public int top;

            public int right;

            public int bottom;
        }

        public enum COMPUTER_NAME_FORMAT
        {
            ComputerNameNetBIOS,
            ComputerNameDnsHostname,
            ComputerNameDnsDomain,
            ComputerNameDnsFullyQualified,
            ComputerNamePhysicalNetBIOS,
            ComputerNamePhysicalDnsHostname,
            ComputerNamePhysicalDnsDomain,
            ComputerNamePhysicalDnsFullyQualified,
            ComputerNameMax
        }

        public struct LSA_UNICODE_STRING
        {
            public ushort Length;

            public ushort MaximumLength;

            [MarshalAs(UnmanagedType.LPWStr)]
            public string Buffer;
        }

        public struct LSA_OBJECT_ATTRIBUTES
        {
            public uint Length;

            public IntPtr RootDirectory;

            public IntPtr ObjectName;

            public uint Attributes;

            public IntPtr SecurityDescriptor;

            public IntPtr SecurityQualityOfService;
        }

        [UnmanagedFunctionPointer(CallingConvention.StdCall)]
        [return: MarshalAs(UnmanagedType.Bool)]
        public delegate bool EnumPowerSchemesProc(uint uiIndex, uint dwName, [MarshalAs(UnmanagedType.LPWStr)] StringBuilder sName, uint dwDesc, [MarshalAs(UnmanagedType.LPWStr)] StringBuilder sDesc, ref POWER_POLICY pp, IntPtr lParam);

        [UnmanagedFunctionPointer(CallingConvention.StdCall)]
        public delegate bool EnumWindowsProc(IntPtr hwnd, IntPtr lparam);

        public const uint NO_ERROR = 0u;

        public const uint PT_LOCAL = 0u;

        public const uint DDD_REMOVE_DEFINITION = 2u;

        public const uint DDD_EXACT_MATCH_ON_REMOVE = 4u;

        public const uint PT_TEMPORARY = 1u;

        public const uint PT_ROAMING = 2u;

        public const uint PT_MANDATORY = 4u;

        public const int WM_HOTKEY = 786;

        public const int MOD_ALT = 1;

        public const int MOD_CONTROL = 2;

        public const int VK_CONTROL = 17;

        public const ulong CM_LOCATE_DEVNODE_NORMAL = 0uL;

        public const int CR_SUCCESS = 0;

        public const ulong CM_REENUMERATE_NORMAL = 0uL;

        public const uint PROCESSBASICINFORMATION = 0u;

        public const int HCF_HIGHCONTRASTON = 1;

        public const int SPI_SETHIGHCONTRAST = 67;

        public const int SPIF_SENDWININICHANGE = 2;

        public const uint STYPE_DISKTREE = 0u;

        public const uint SECURITY_DESCRIPTOR_REVISION = 1u;

        public const uint NO_INHERITANCE = 0u;

        public const uint ERROR_NONE_MAPPED = 1332u;

        public const uint RESOURCETYPE_DISK = 1u;

        public const uint CONNECT_UPDATE_PROFILE = 1u;

        public const int GCL_HICON = -14;

        public const int GCL_HICONSM = -34;

        public const uint WM_GETICON = 127u;

        public const uint WM_CLOSE = 16u;

        public const uint SHTDN_REASON_FLAG_PLANNED = 2147483648u;

        public const uint EWX_FORCEIFHUNG = 16u;

        public const uint NETSETUP_JOIN_DOMAIN = 1u;

        public const uint NETSETUP_ACCT_CREATE = 2u;

        public const uint NETSETUP_DOMAIN_JOIN_IF_JOINED = 32u;

        public const uint NETSETUP_ACCT_DELETE = 2u;

        public const uint PROCESS_VM_READ = 16u;

        public const uint PROCESS_QUERY_INFORMATION = 1024u;

        public const uint SC_ENUM_PROCESS_INFO = 0u;

        public const uint SC_MANAGER_ENUMERATE_SERVICE = 4u;

        public const uint SC_MANAGER_CREATE_SERVICE = 2u;

        public const uint SC_MANAGER_ALL_ACCESS = 983103u;

        public const uint SERVICE_DELETE = 65536u;

        public const uint SERVICE_QUERY_CONFIG = 1u;

        public const uint SERVICE_CHANGE_CONFIG = 2u;

        public const uint SERVICE_WIN32 = 48u;

        public const uint SERVICE_DRIVER = 11u;

        public const uint SERVICE_NO_CHANGE = uint.MaxValue;

        public const uint SERVICE_ACTIVE = 1u;

        public const uint SERVICE_ALL_ACCESS = 983551u;

        public const uint SERVICE_WIN32_OWN_PROCESS = 16u;

        public const uint SERVICE_ERROR_NORMAL = 1u;

        public const int ERROR_INSUFFICIENT_BUFFER = 122;

        public const uint ERROR_NO_DATA = 232u;

        public const int HWND_TOPMOST = -1;

        public const int HWND_NOTOPMOST = -2;

        public const int SWP_NOMOVE = 2;

        public const int SWP_NOSIZE = 1;

        public const int CREATE_NEW_CONSOLE = 16;

        public const int CREATE_UNICODE_ENVIRONMENT = 1024;

        public const int WM_FONTCHANGE = 29;

        public static readonly IntPtr HWND_BROADCAST = new IntPtr(65535);

        [DllImport("Wtsapi32.dll", EntryPoint = "WTSQuerySessionInformationW", SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool WTSQuerySessionInformation(IntPtr hServer, uint SessionId, WTS_INFO_CLASS WTSInfoClass, ref IntPtr ppBuffer, ref uint pBytesReturned);

        [DllImport("Wtsapi32.dll")]
        public static extern void WTSFreeMemory(IntPtr pMemory);

        [DllImport("Wtsapi32.dll", EntryPoint = "WTSEnumerateSessionsW", SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool WTSEnumerateSessions(IntPtr hServer, uint Reserved, uint Version, ref IntPtr ppSessionInfo, ref uint pCount);

        [DllImport("logoncli.dll", SetLastError = true)]
        public static extern int NetIsServiceAccount([In][MarshalAs(UnmanagedType.LPWStr)] string ServerName, [In][MarshalAs(UnmanagedType.LPWStr)] string AccountName, out int IsService);

        [DllImport("logoncli.dll", SetLastError = true)]
        public static extern int NetRemoveServiceAccount([In][MarshalAs(UnmanagedType.LPWStr)] string ServerName, [In][MarshalAs(UnmanagedType.LPWStr)] string AccountName, uint Flags);

        [DllImport("logoncli.dll", SetLastError = true)]
        public static extern int NetAddServiceAccount([In][MarshalAs(UnmanagedType.LPWStr)] string ServerName, [In][MarshalAs(UnmanagedType.LPWStr)] string AccountName, [In][MarshalAs(UnmanagedType.LPWStr)] string Reserved, uint Flags);

        [DllImport("advapi32.dll", SetLastError = true)]
        public static extern uint LsaNtStatusToWinError(uint Status);

        [DllImport("advapi32.dll", SetLastError = true)]
        public static extern uint LsaOpenPolicy(ref LSA_UNICODE_STRING SystemName, ref LSA_OBJECT_ATTRIBUTES ObjectAttributes, LSA_POLICY_ACCESS_MASK DesiredAccess, ref IntPtr PolicyHandle);

        [DllImport("advapi32.dll", SetLastError = true)]
        public static extern uint LsaClose(IntPtr ObjectHandle);

        [DllImport("advapi32.dll", SetLastError = true)]
        public static extern uint LsaAddAccountRights(IntPtr PolicyHandle, [In] byte[] AccountSid, [In] ref LSA_UNICODE_STRING UserRights, uint CountOfRights);

        [DllImport("advapi32.dll", SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool QueryServiceStatusEx([In] IntPtr hService, uint InfoLevel, IntPtr lpBuffer, uint cbBufSize, out uint pcbBytesNeeded);

        [DllImport("advapi32.dll", SetLastError = true)]
        public static extern bool ControlService(IntPtr hService, SERVICE_CONTROL_CODES dwControl, ref SERVICE_STATUS_PROCESS lpServiceStatus);

        [DllImport("advapi32.dll", EntryPoint = "ChangeServiceConfigW", SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool ChangeServiceConfig([In] IntPtr hService, uint dwServiceType, uint dwStartType, uint dwErrorControl, [In][MarshalAs(UnmanagedType.LPWStr)] string lpBinaryPathName, [In][MarshalAs(UnmanagedType.LPWStr)] string lpLoadOrderGroup, IntPtr lpdwTagId, [In][MarshalAs(UnmanagedType.LPWStr)] string lpDependencies, [In][MarshalAs(UnmanagedType.LPWStr)] string lpServiceStartName, [In][MarshalAs(UnmanagedType.LPWStr)] string lpPassword, [In][MarshalAs(UnmanagedType.LPWStr)] string lpDisplayName);

        [DllImport("advapi32.dll", EntryPoint = "QueryServiceConfigW", SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool QueryServiceConfig([In] IntPtr hService, [Out] IntPtr lpServiceConfig, uint cbBufSize, out uint pcbBytesNeeded);

        [DllImport("kernel32.dll", EntryPoint = "DefineDosDeviceW", SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool DefineDosDevice(uint dwFlags, [In][MarshalAs(UnmanagedType.LPWStr)] string lpDeviceName, [In][MarshalAs(UnmanagedType.LPWStr)] string lpTargetPath);

        [DllImport("Netapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
        public static extern int NetShareEnum([MarshalAs(UnmanagedType.LPWStr)] string ServerName, int level, ref IntPtr BufPtr, int prefmaxbufferlen, ref int entriesread, ref int totalentries, ref IntPtr resume_handle);

        [DllImport("Netapi32.dll", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Unicode, SetLastError = true)]
        public static extern NET_API_STATUS NetApiBufferFree([In] IntPtr Buffer);

        [DllImport("Netapi32.dll", EntryPoint = "DsGetDcNameW", SetLastError = true)]
        internal static extern uint DsGetDcName([In][MarshalAs(UnmanagedType.LPTStr)] string computerName, [In][MarshalAs(UnmanagedType.LPTStr)] string domainName, [In] IntPtr domainGuid, [In][MarshalAs(UnmanagedType.LPTStr)] string siteName, [In] int flags, out IntPtr domainControllerInfo);

        [DllImport("advapi32.dll", EntryPoint = "LookupAccountSidW", SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool LookupAccountSid([In][MarshalAs(UnmanagedType.LPWStr)] string lpSystemName, [In] byte[] lpSid, [Out][MarshalAs(UnmanagedType.LPWStr)] StringBuilder lpName, ref uint cchName, [Out][MarshalAs(UnmanagedType.LPWStr)] StringBuilder lpReferencedDomainName, ref uint cchReferencedDomainName, out SID_NAME_USE peUse);

        [DllImport("kernel32.dll", SetLastError = true)]
        public static extern uint WTSGetActiveConsoleSessionId();

        [DllImport("Wtsapi32.dll", SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool WTSQueryUserToken(uint SessionId, ref IntPtr phToken);

        [DllImport("advapi32.dll", EntryPoint = "CreateProcessAsUserW", SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool CreateProcessAsUser([In] IntPtr hToken, [In][MarshalAs(UnmanagedType.LPWStr)] string lpApplicationName, [In][Out][MarshalAs(UnmanagedType.LPWStr)] string lpCommandLine, [In] IntPtr lpProcessAttributes, [In] IntPtr lpThreadAttributes, [MarshalAs(UnmanagedType.Bool)] bool bInheritHandles, uint dwCreationFlags, [In] IntPtr lpEnvironment, [In][MarshalAs(UnmanagedType.LPWStr)] string lpCurrentDirectory, [In] ref STARTUPINFO lpStartupInfo, out PROCESS_INFORMATION lpProcessInformation);

        [DllImport("Userenv.dll", SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool DestroyEnvironmentBlock([In] IntPtr lpEnvironment);

        [DllImport("Userenv.dll", SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool CreateEnvironmentBlock(out IntPtr lpEnvironment, [In] IntPtr hToken, [MarshalAs(UnmanagedType.Bool)] bool bInherit);

        [DllImport("kernel32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool AllocConsole();

        [DllImport("kernel32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool FreeConsole();

        [DllImport("gdi32.dll", EntryPoint = "AddFontResourceW", SetLastError = true)]
        public static extern int AddFontResource([In][MarshalAs(UnmanagedType.LPTStr)] string lpszFilename);

        [DllImport("gdi32.dll", EntryPoint = "RemoveFontResourceW", SetLastError = true)]
        public static extern int RemoveFontResource([In][MarshalAs(UnmanagedType.LPTStr)] string lpszFilename);

        [DllImport("user32.dll", SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool SetWindowPos([In] IntPtr hWnd, [In] IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags);

        [DllImport("user32.dll", SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool GetWindowRect([In] IntPtr hWnd, out RECT lpRect);

        [DllImport("Userenv.dll", EntryPoint = "DeleteProfileW", SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool DeleteProfile([In][MarshalAs(UnmanagedType.LPTStr)] string lpSidString, [In][MarshalAs(UnmanagedType.LPTStr)] string lpProfilePath, [In][MarshalAs(UnmanagedType.LPTStr)] string lpComputerName);

        [DllImport("kernel32.dll", EntryPoint = "SetComputerNameExW", SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool SetComputerNameEx(COMPUTER_NAME_FORMAT NameType, [In][MarshalAs(UnmanagedType.LPWStr)] string lpBuffer);

        [DllImport("Netapi32.dll", SetLastError = true)]
        public static extern NET_API_STATUS NetRenameMachineInDomain([In][MarshalAs(UnmanagedType.LPWStr)] string lpServer, [In][MarshalAs(UnmanagedType.LPWStr)] string lpNewMachineName, [In][MarshalAs(UnmanagedType.LPWStr)] string lpAccount, [In][MarshalAs(UnmanagedType.LPWStr)] string lpPassword, uint fRenameOptions);

        [DllImport("shell32.dll", EntryPoint = "SHQueryRecycleBinW")]
        public static extern int SHQueryRecycleBin([In][MarshalAs(UnmanagedType.LPTStr)] string pszRootPath, ref SHQUERYRBINFO pSHQueryRBInfo);

        [DllImport("shell32.dll", CallingConvention = CallingConvention.StdCall, EntryPoint = "SHEmptyRecycleBinW", SetLastError = true)]
        public static extern int SHEmptyRecycleBin(IntPtr hwnd, [In][MarshalAs(UnmanagedType.LPWStr)] string pszRootPath, uint dwFlags);

        [DllImport("Userenv.dll", EntryPoint = "GetProfilesDirectoryW", SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool GetProfilesDirectory([Out][MarshalAs(UnmanagedType.LPTStr)] StringBuilder lpProfilesDir, ref uint lpcchSize);

        [DllImport("PowrProf.dll", SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool EnumPwrSchemes(EnumPowerSchemesProc lpfnPwrSchemesEnumProc, IntPtr lParam);

        [DllImport("PowrProf.dll", SetLastError = true)]
        public static extern bool SetActivePwrScheme(uint uiID, [In] IntPtr lpGlobalPowerPolicy, [In] IntPtr lpPowerPolicy);

        [DllImport("PowrProf.dll", SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool GetActivePwrScheme(out uint uiID);

        [DllImport("user32.dll", SetLastError = true)]
        public static extern IntPtr FindWindowW([In][MarshalAs(UnmanagedType.LPWStr)] string lpClassName, [In][MarshalAs(UnmanagedType.LPWStr)] string lpWindowName);

        [DllImport("user32.dll", SetLastError = true)]
        public static extern IntPtr FindWindowExW([In] IntPtr hWndParent, [In] IntPtr hWndChildAfter, [In][MarshalAs(UnmanagedType.LPWStr)] string lpszClass, [In][MarshalAs(UnmanagedType.LPWStr)] string lpszWindow);

        [DllImport("advapi32.dll", SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool DeleteService(IntPtr hService);

        [DllImport("advapi32.dll", EntryPoint = "StartServiceW", SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool StartService([In] IntPtr hService, uint dwNumServiceArgs, IntPtr lpServiceArgVectors);

        [DllImport("advapi32.dll", EntryPoint = "OpenServiceW", SetLastError = true)]
        public static extern IntPtr OpenService([In] IntPtr hSCManager, [In][MarshalAs(UnmanagedType.LPWStr)] string lpServiceName, uint dwDesiredAccess);

        [DllImport("advapi32.dll", EntryPoint = "CreateServiceW", SetLastError = true)]
        public static extern IntPtr CreateService([In] IntPtr hSCManager, [In][MarshalAs(UnmanagedType.LPWStr)] string lpServiceName, [In][MarshalAs(UnmanagedType.LPWStr)] string lpDisplayName, uint dwDesiredAccess, uint dwServiceType, uint dwStartType, uint dwErrorControl, [In][MarshalAs(UnmanagedType.LPWStr)] string lpBinaryPathName, [In][MarshalAs(UnmanagedType.LPWStr)] string lpLoadOrderGroup, IntPtr lpdwTagId, [In][MarshalAs(UnmanagedType.LPWStr)] string lpDependencies, [In][MarshalAs(UnmanagedType.LPWStr)] string lpServiceStartName, [In][MarshalAs(UnmanagedType.LPWStr)] string lpPassword);

        [DllImport("advapi32.dll", EntryPoint = "EnumServicesStatusExW", SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool EnumServicesStatusEx([In] IntPtr hSCManager, uint InfoLevel, uint dwServiceType, uint dwServiceState, IntPtr lpServices, uint cbBufSize, out uint pcbBytesNeeded, out uint lpServicesReturned, IntPtr lpResumeHandle, [In][MarshalAs(UnmanagedType.LPWStr)] string pszGroupName);

        [DllImport("advapi32.dll", EntryPoint = "OpenSCManagerW", SetLastError = true)]
        public static extern IntPtr OpenSCManager([In][MarshalAs(UnmanagedType.LPWStr)] string lpMachineName, [In][MarshalAs(UnmanagedType.LPWStr)] string lpDatabaseName, uint dwDesiredAccess);

        [DllImport("advapi32.dll", SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool CloseServiceHandle([In] IntPtr hSCObject);

        [DllImport("kernel32.dll", SetLastError = true)]
        public static extern IntPtr OpenProcess(uint dwDesiredAccess, [MarshalAs(UnmanagedType.Bool)] bool bInheritHandle, uint dwProcessId);

        [DllImport("user32.dll", SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool FlashWindowEx([In] ref FLASHWINFO pfwi);

        [DllImport("kernel32.dll", SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool ReadProcessMemory([In] IntPtr hProcess, [In] IntPtr lpBaseAddress, [Out] byte[] lpBuffer, uint nSize, out uint lpNumberOfBytesRead);

        [DllImport("kernel32.dll", SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool CloseHandle(IntPtr hObject);

        [DllImport("Iphlpapi.dll", SetLastError = true)]
        public static extern uint GetInterfaceInfo([Out] IntPtr pIfTable, ref uint dwOutBufLen);

        [DllImport("Iphlpapi.dll", SetLastError = true)]
        public static extern uint IpReleaseAddress(ref IP_ADAPTER_INDEX_MAP AdapterInfo);

        [DllImport("Iphlpapi.dll", SetLastError = true)]
        public static extern uint IpRenewAddress(ref IP_ADAPTER_INDEX_MAP AdapterInfo);

        [DllImport("kernel32.dll", SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool FreeLibrary([In] IntPtr hLibModule);

        [DllImport("kernel32.dll", EntryPoint = "LoadLibraryW", SetLastError = true)]
        public static extern IntPtr LoadLibrary([In][MarshalAs(UnmanagedType.LPWStr)] string lpLibFileName);

        [DllImport("user32.dll", EntryPoint = "LoadStringW", SetLastError = true)]
        public static extern int LoadString([In] IntPtr hInstance, uint uID, [Out][MarshalAs(UnmanagedType.LPWStr)] StringBuilder lpBuffer, int cchBufferMax);

        [DllImport("user32.dll", SetLastError = true)]
        public static extern IntPtr GetDC([In] IntPtr hWnd);

        [DllImport("user32.dll", SetLastError = true)]
        public static extern int ReleaseDC([In] IntPtr hWnd, [In] IntPtr hDC);

        [DllImport("Netapi32.dll", SetLastError = true)]
        public static extern NET_API_STATUS NetUnjoinDomain([In][MarshalAs(UnmanagedType.LPWStr)] string lpServer, [In][MarshalAs(UnmanagedType.LPWStr)] string lpAccount, [In][MarshalAs(UnmanagedType.LPWStr)] string lpPassword, uint fUnjoinOptions);

        [DllImport("Netapi32.dll", SetLastError = true)]
        public static extern NET_API_STATUS NetJoinDomain([In][MarshalAs(UnmanagedType.LPWStr)] string lpServer, [In][MarshalAs(UnmanagedType.LPWStr)] string lpDomain, [In][MarshalAs(UnmanagedType.LPWStr)] string lpAccountOU, [In][MarshalAs(UnmanagedType.LPWStr)] string lpAccount, [In][MarshalAs(UnmanagedType.LPWStr)] string lpPassword, uint fJoinOptions);

        [DllImport("user32.dll", SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool ExitWindowsEx(uint uFlags, uint dwReason);

        [DllImport("user32.dll", SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool EnumChildWindows([In] IntPtr hWndParent, EnumWindowsProc lpEnumFunc, [MarshalAs(UnmanagedType.SysInt)] IntPtr lParam);

        [DllImport("user32.dll", SetLastError = true)]
        public static extern IntPtr SetParent([In] IntPtr hWndChild, [In] IntPtr hWndNewParent);

        [DllImport("user32.dll", EntryPoint = "SendMessageW", SetLastError = true)]
        public static extern IntPtr SendMessage([In] IntPtr hWnd, uint Msg, uint wParam, int lParam);

        [DllImport("user32.dll", EntryPoint = "GetClassLongW", SetLastError = true)]
        public static extern IntPtr GetClassLong([In] IntPtr hWnd, int nIndex);

        [DllImport("user32.dll", EntryPoint = "GetClassLongPtrW", SetLastError = true)]
        public static extern IntPtr GetClassLongPtr([In] IntPtr hWnd, int nIndex);

        [DllImport("user32.dll", SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool EnumWindows(EnumWindowsProc lpEnumFunc, [MarshalAs(UnmanagedType.SysInt)] IntPtr lParam);

        [DllImport("user32.dll", SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool IsWindowVisible([In] IntPtr hWnd);

        [DllImport("user32.dll", EntryPoint = "GetWindowTextW", SetLastError = true)]
        public static extern int GetWindowText([In] IntPtr hWnd, [Out][MarshalAs(UnmanagedType.LPWStr)] StringBuilder lpString, int nMaxCount);

        [DllImport("user32.dll", EntryPoint = "GetWindowTextLengthW", SetLastError = true)]
        public static extern int GetWindowTextLength([In] IntPtr hWnd);

        [DllImport("user32.dll", SetLastError = true)]
        public static extern uint GetWindowThreadProcessId([In] IntPtr hWnd, out int lpdwProcessId);

        [DllImport("user32.dll", EntryPoint = "GetClassNameW", SetLastError = true)]
        public static extern int GetClassName([In] IntPtr hWnd, [Out][MarshalAs(UnmanagedType.LPWStr)] StringBuilder lpClassName, int nMaxCount);

        [DllImport("Kernel32.dll", EntryPoint = "GetDiskFreeSpaceExW", SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool GetDiskFreeSpaceEx([In][MarshalAs(UnmanagedType.LPWStr)] string lpDirectoryName, ref ulong lpFreeBytesAvailable, ref ulong lpTotalNumberOfBytes, ref ulong lpTotalNumberOfFreeBytes);

        [DllImport("mpr.dll", EntryPoint = "WNetCancelConnection2W", SetLastError = true)]
        public static extern uint WNetCancelConnection([In][MarshalAs(UnmanagedType.LPWStr)] string lpName, uint dwFlags, [MarshalAs(UnmanagedType.Bool)] bool fForce);

        [DllImport("mpr.dll", EntryPoint = "WNetAddConnection2W", SetLastError = true)]
        public static extern uint WNetAddConnection2(ref NETRESOURCE lpNetResource, [In][MarshalAs(UnmanagedType.LPWStr)] string lpPassword, [In][MarshalAs(UnmanagedType.LPWStr)] string lpUserName, uint dwFlags);

        [DllImport("netapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
        public static extern NET_API_STATUS NetShareAdd([In][MarshalAs(UnmanagedType.LPWStr)] string servername, uint level, [In] ref SHARE_INFO_502 buf, out int parm_err);

        [DllImport("advapi32.dll", SetLastError = true)]
        public static extern uint InitializeSecurityDescriptor(ref SECURITY_DESCRIPTOR pSecurityDescriptor, uint dwRevision);

        [DllImport("advapi32.dll", EntryPoint = "SetEntriesInAclW", SetLastError = true)]
        public static extern uint SetEntriesInAcl(int cCountOfExplicitEntries, [In] ref EXPLICIT_ACCESS pListOfExplicitEntries, [In] IntPtr OldAcl, ref IntPtr NewAcl);

        [DllImport("advapi32.dll", SetLastError = true)]
        public static extern uint SetSecurityDescriptorDacl(ref SECURITY_DESCRIPTOR pSecurityDescriptor, [MarshalAs(UnmanagedType.Bool)] bool bDaclPresent, [In] IntPtr pDacl, [MarshalAs(UnmanagedType.Bool)] bool bDaclDefaulted);

        [DllImport("advapi32.dll", SetLastError = true)]
        public static extern uint IsValidSecurityDescriptor(ref SECURITY_DESCRIPTOR pSecurityDescriptor);

        [DllImport("user32.dll", SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool SystemParametersInfoW(uint uiAction, uint uiParam, IntPtr pvParam, uint fWinIni);

        [DllImport("netapi32.dll", SetLastError = true)]
        public static extern NET_API_STATUS NetShareAdd([In][MarshalAs(UnmanagedType.LPWStr)] string servername, uint level, [In] ref SHARE_INFO_2 buf, out uint parm_err);

        [DllImport("mpr.dll", SetLastError = true)]
        public static extern int WNetGetConnection(string lpLocalName, StringBuilder lpRemoteName, ref int lpnLength);

        [DllImport("Userenv.dll", SetLastError = true)]
        public static extern bool GetProfileType(ref uint pdwflags);

        [DllImport("user32.dll", SetLastError = true)]
        public static extern IntPtr GetForegroundWindow();

        [DllImport("user32.dll", SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool ShowWindow(IntPtr hwnd, int nCmdShow);

        [DllImport("user32.dll", SetLastError = true)]
        public static extern bool RegisterHotKey(IntPtr hWnd, int id, uint fsModifiers, uint vk);

        [DllImport("user32.dll", SetLastError = true)]
        public static extern bool UnregisterHotKey(IntPtr hWnd, int id);

        [DllImport("Cfgmgr32.dll", SetLastError = true)]
        public static extern uint CM_Reenumerate_DevNode(uint dnDevInst, ulong ulFlags);

        [DllImport("Cfgmgr32.dll", SetLastError = true)]
        public static extern uint CM_Locate_DevNode(ref uint PdnDevInst, int pDeviceID, ulong ulFlags);

        [DllImport("ntdll.dll", SetLastError = true)]
        public static extern int NtQueryInformationProcess(IntPtr handle, uint processinformationclass, ref Process_Basic_Information ProcessInformation, int ProcessInformationLength, ref uint ReturnLength);

        [DllImport("shell32.dll", CallingConvention = CallingConvention.StdCall, EntryPoint = "ExtractIconExW", SetLastError = true)]
        public static extern uint ExtractIconEx([In][MarshalAs(UnmanagedType.LPWStr)] string lpszFile, int nIconIndex, ref IntPtr phiconLarge, ref IntPtr phiconSmall, uint nIcons);

        [DllImport("user32.dll", SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool DestroyIcon([In] IntPtr hIcon);

        [DllImport("kernel32.dll", SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool IsWow64Process([In] IntPtr hProcess, out bool Wow64Process);

        [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
        public static extern IntPtr GetModuleHandle(string moduleName);

        [DllImport("kernel32.dll", CharSet = CharSet.Ansi, ExactSpelling = true, SetLastError = true)]
        public static extern IntPtr GetProcAddress(IntPtr hModule, string methodName);
    }
}

另外附上如何安装我们自己开发的Windows服务步骤

1.以管理员身份运行cmd

2.安装windows服务

  cd C:\Windows\Microsoft.NET\Framework\v4.0.30319(InstallUtil.exe的路径,注意InstallUtil.exe的版本号需要和项目的版本号相同)

3.安装windows服务

  InstallUtil.exe D:\项目相关文件\MonitoringTEST\DialTest\bin\Debug\ProjectTest.exe(项目的路径)

InstallUtil.exe "D:\VisualStudio Files\Web.Server.Api\Web.Server.Api\bin\Debug\Web.Server.Api.exe"

4.启动windows服务

  net start TestServive(服务名称)

卸载windows服务

  InstallUtil.exe /u D:\项目相关文件\MonitoringTEST\DialTest\bin\Debug\ProjectTest.exe

参考文章:

百度关键词搜索:C#在windows服务中启动第三方exe可执行程序

Windows服务(C#)显式运行exe程序 | 认知自我

在Windows中启动或停止服务的4种方法 | 多听号 (duotin.com)

在window service中调用外部exe或.bat等_windows服务 启动exe文件-CSDN博客

Windows服务(C#)显式运行exe程序 - 六镇2012 - 博客园 (cnblogs.com)

C# windows服务中启动带UI界面的程序_c#在桌面前启动程序-CSDN博客

C#服务出错:没有 RunInstallerAttribute.Yes 的公共安装程序-CSDN博客

window service 中调用外部exe-CSDN社区

在windows服务中调用第三方exe可执行程序

文章来源:https://blog.csdn.net/Elegant_Kevin/article/details/135367975
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。