C# windows服务程序开机自启动exe程序
我们使用传统的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 Enumerationsenum 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 Constantspublic 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);#endregionpublic 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.以管理员身份运行cmd2.安装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可执行程序】
相关文章:
C# windows服务程序开机自启动exe程序
我们使用传统的Process.Start(".exe")启动进程会遇到无法打开UI界面的问题,尤其是我们需要进行开启自启动程序设置时出现诸多问题,于是我们就想到采用windows服务开机自启动来创建启动一个新的exe程序,并且是显式运行。 首先是打开…...
【SpringMVC】常用注解
什么是MVC? MVC是一种程序分层开发模式,分别是Model(模型),View(视图)以及Controller(控制器)。这样做可以将程序的用户界面和业务逻辑分离,使得代码具有良好…...
关于曲率、曲率半径和曲率圆,看这几篇文章就够啦
关于曲率、曲率半径和曲率圆的内容,是考研数学数学一和数学二大纲中明确要求掌握的内容,但这部分内容在很多教材教辅以及练习题中较少涉及。在本文中,荒原之梦考研数学网就为大家整理了曲率、曲率半径和曲率圆方程相关的概念、基础知识以及练…...
java面试题-Spring常见的异常类有哪些?
远离八股文,面试大白话,通俗且易懂 看完后试着用自己的话复述出来。有问题请指出,有需要帮助理解的或者遇到的真实面试题不知道怎么总结的也请评论中写出来,大家一起解决。 java面试题汇总-目录-持续更新中 NullPointerException&…...
数据库选择题 (期末复习)
数据库第一章 概论简答题 数据库第二章 关系数据库简答题 数据库第三章 SQL简答题 数据库第四第五章 安全性和完整性简答题 数据库第七章 数据库设计简答题 数据库第九章 查询处理和优化简答题 数据库第十第十一章 恢复和并发简答题 2015期末 1、在数据库中,下列说…...
WeNet语音识别+Qwen-72B-Chat Bot+Sambert-Hifigan语音合成
WeNet语音识别Qwen-72B-Chat Bot👾Sambert-Hifigan语音合成 简介 利用 WeNet 进行语音识别,使用户能够通过语音输入与系统进行交互。接着,Qwen-72B-Chat Bot作为聊天机器人接收用户的语音输入或文本输入,提供响应并与用户进行对话…...
是否需要跟上鸿蒙(OpenHarmony)开发岗位热潮?
前言 自打华为2019年发布鸿蒙操作系统以来,网上各种声音百家争鸣。尤其是2023年发布会公布的鸿蒙4.0宣称不再支持Android,更激烈的讨论随之而来。 本文没有宏大的叙事,只有基于现实的考量。 通过本文,你将了解到: Har…...
【Golang】Json 无法表示 float64 类型的 NaN 以及 Inf 导致的 panic
【Golang】Json 无法表示 float64 类型的 NaN 以及 Inf 导致的 panic 原因 golang 服务出现了 panic,根据 panic 打印出的堆栈找到了问题代码,看上去原因是:json 序列化时,遇到了无法序列化的内容 [panic]: json: unsupported …...
bootstrap5实现宠物商店网站 Cat-Master
一、需求分析 宠物商店网站是指专门为宠物商店或宠物用品商家而建立的在线平台。这种网站的功能通常旨在提供以下服务: 产品展示:宠物商店网站通常会展示宠物食品、玩具、床上用品、健康护理产品等各种宠物用品的图片和详细信息。这样,潜在的…...
基于多反应堆的高并发服务器【C/C++/Reactor】(中)创建并初始化TcpServer实例 以及 启动
对于一个TcpServer来说,它的灵魂是什么?就是需要提供一个事件循环EventLop(EventLoop),不停地去检测有没有客户端的连接到达,有没有客户端给服务器发送数据,描述的这些动作,反应堆模型能够胜任。当服务器和…...
边缘计算设备是什么意思。
问题描述:边缘计算设备是什么意思。 问题解答: 边缘计算(Edge Computing)是一种计算模型,其主要思想是在距离数据产生源头更近的地方进行数据处理和计算,而不是将所有数据传输到远程云服务器进行处理。边…...
使用ChatGPT midjourney 等AI智能工具,能为视觉营销做些什么?
使用ChatGPT、Midjourney等AI智能工具,可以极大地提升视觉营销的效率和创意水平。以下是这些工具在视觉营销中的一些具体应用: 内容创作与文案撰写(ChatGPT) 广告文案生成:根据产品特点和目标受众,生成吸…...
图像分割实战-系列教程4:unet医学细胞分割实战2(医学数据集、图像分割、语义分割、unet网络、代码逐行解读)
🍁🍁🍁图像分割实战-系列教程 总目录 有任何问题欢迎在下面留言 本篇文章的代码运行界面均在Pycharm中进行 本篇文章配套的代码资源已经上传 unet医学细胞分割实战1 unet医学细胞分割实战2 unet医学细胞分割实战3 unet医学细胞分割实战4 unet…...
防火墙未开端口导致zookeeper集群异常,kafka起不来
转载说明:如果您喜欢这篇文章并打算转载它,请私信作者取得授权。感谢您喜爱本文,请文明转载,谢谢。 问题描述: 主机信息: IPhostname10.0.0.10host1010.0.0.12host1210.0.0.13host13 在这三台主机上部署…...
React-hook-form-mui(二):表单数据处理
前言 在上一篇文章中,我们介绍了react-hook-form-mui的基础用法。本文将着表单数据处理。 react-hook-form-mui提供了丰富的表单数据处理功能,可以通过watch属性来获取表单数据。 Demo 下面是一个使用watch属性的例子: import React from…...
java网络文件地址url的转换为MultipartFile文件流
废话不多说,直接上代码 一、异常捕捉类 public class BusinessException extends RuntimeException {public BusinessException(String msg){super(msg);} }二、转换类 package com.example.answer_system.utils;import org.springframework.mock.web.MockMultipa…...
JS实现/封装节流函数
封装节流函数 节流原理:在一定时间内,只能触发一次 let timer, flag; /*** 节流原理:在一定时间内,只能触发一次* * param {Function} func 要执行的回调函数 * param {Number} wait 延时的时间* param {Boolean} immediate 是否立…...
ENVI 各版本安装指南
ENVI下载链接 https://pan.baidu.com/s/1APpjHHSsrXMaCcJUQGmFBA?pwd0531 1.鼠标右击【ENVI 5.6(64bit)】压缩包(win11及以上系统需先点击“显示更多选项”)选择【解压到 ENVI 5.6(64bit)】。 2.打开解压后的文件夹,…...
60天零基础干翻C++————初识C++
初识c 命名空间命名空间的定义命名空间的使用 输入输出流缺省参数引用引用定义常量的引用引用的使用场景做函数参数引用做返回值 命名空间 命名空间的定义 在c语言中会有下面问题 上述代码中,全局变量rand 可能会命名冲突,如下图 此时编译失败&…...
考研复试英语口语问答举例第二弹
考研复试英语口语问答举例第二弹 文章目录 考研复试英语口语问答举例第二弹Question :介绍你的读研兴趣与动机Answer11:(自动化控制方向)Answer12:(集成电路方向)Answer13:ÿ…...
MyBatis-Plus实现自定义SQL语句的分页查询
正常开发的时候,有时候要写一个多表查询,然后多表查询之后还需要分页,MyBatis-Plus的分页插件功能挺不错的,可以很简单实现自定义SQL的分页查询。 分页插件配置 import com.baomidou.mybatisplus.annotation.DbType; import com…...
vue3 里的 ts 类型工具函数
目录 前言一、PropType\<T>二、MaybeRef\<T>三、MaybeRefOrGetter\<T>四、ExtractPropTypes\<T>五、ExtractPublicPropTypes\<T>六、ComponentCustomProperties七、ComponentCustomOptions八、ComponentCustomProps九、CSSProperties 前言 相关 …...
【SpringCloud】之远程消费(进阶使用)
🎉🎉欢迎来到我的CSDN主页!🎉🎉 🏅我是君易--鑨,一个在CSDN分享笔记的博主。📚📚 🌟推荐给大家我的博客专栏《SpringCloud开发之远程消费》。🎯&a…...
自然语言处理24-T5模型的介绍与训练过程,利用简单构造数据训练微调该模型,体验整个过程
大家好,我是微学AI,今天给大家介绍一下自然语言处理24-T5模型的介绍与训练过程,利用简单构造数据训练微调该模型,体验整个过程。在大模型ChatGPT发布之前,NLP领域是BERT,T5模型为主导,T5(Text-to-Text Transfer Transformer)是一种由Google Brain团队在2019年提出的自然…...
CISSP 第5章 保护资产的安全
1、资产识别和分类 1.1 敏感数据 1.1.1 定义 敏感数据是任何非公开或非机密的信息,包括机密的、专有的、受保护的或因其对组织的价值或按照现有的法律和法规而需要组织保护的任何其他类型的数据。 1.1.2 个人身份信息PII 个人身份信息(PII)…...
docker安装-在linux下的安装步骤
#切换到root用户 su yum安装jcc相关 yum -y install gcc yum -y install gcc-c 安装yum-utils sudo yum install -y yum-utils 设置stable镜像仓库 sudo yum-config-manager --add-repo https://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo 更新yum软件包索…...
在Uniapp中使用Echarts创建可视化图表
在uniapp中可以引入echarts创建数据可视化图表。 1. 安装Echarts 使用npm安装echarts插件,命令如下: npm install echarts --save2. 引入Eharts 在需要使用Echarts的页面引入: import *as echarts from echarts3. 创建实例 创建画布元素…...
基于python的leetcode算法介绍之动态规划
文章目录 零 算法介绍一 例题介绍 使用最小花费爬楼梯问题分析 Leetcode例题与思路[118. 杨辉三角](https://leetcode.cn/problems/pascals-triangle/)解题思路题解 [53. 最大子数组和](https://leetcode.cn/problems/maximum-subarray/)解题思路题解 [96. 不同的二叉搜索树](h…...
通信原理期末复习——计算大题(一)
个人名片: 🦁作者简介:一名喜欢分享和记录学习的在校大学生 🐯个人主页:妄北y 🐧个人QQ:2061314755 🐻个人邮箱:2061314755qq.com 🦉个人WeChat:V…...
【萤火虫系列教程】2/5-Adobe Firefly 文字生成图像
文字生成图像 登录账号后,在主页点击文字生成图像的【生成】按钮,进入到文字生成图像 查看图像 在文字生成图像页面,可以看到别人生成的图像。 点击某个图像,就可以进入图像详情,可以看到文字描述。 生成图像 我…...
西安单位网站制作/网络推广的优势有哪些
文章目录1背景2传感器2.1光电编码1背景 由于移动机器人车体的非线体轮胎与地面的轻微滑动和非完整约束等原因。无法建立一个精确数学模型.使许多基于模型的移动机器人运动方案存在困难 移动机器人的运动控制。精确地进行自定位是一个基本的要求/自定位就是获得机器人相对于一个…...
济南做网络安全的公司/手机网站怎么优化
2019独角兽企业重金招聘Python工程师标准>>> 权声明:本文为博主原创文章,未经博主允许不得转载。 一、使用CM添加服务的方式安装Oozie 如果在创建Oozie数据库时失败,且提示数据库已存在,如下图,则可能是之前…...
贵阳的网站建设公司/长沙seo推广外包
在IOS开发中,要做字典转模型一般情况如下: 1 /**2 * 声明方法3 */4 - (instancetype) initWithDictionary:(NSDictionary *)dict;5 (instancetype) carWithDictionary:(NSDictionary *)dict;6 7 /**8 * 实现方法9 */ 10 - (instancetype)initWith…...
wordpress页面添加主页/宁波 seo整体优化
一般的变量声明时就创建相应的内存空间,该空间用于存储该变量的值。函数进行按值传递时,是将该变量值的拷贝传给函数,因此在函数中将传进来的值改变也不能改变变量的值。指针变量和按指针传递。指针类型的变量在声明后,根据操作系…...
宁波建网站哪家/营销渠道管理
volatile是易变的、不稳定的意思。有些人根本没见过这个关键字,也有的程序员知道他的存在,但没有使用过它,嵌入式系统程序员经常同硬件、中断、RTOS等等打交道,所有这些都要求使用volatile变量。不懂得volatile内容将会带来灾难。…...
吉林省建设工程造价网站/推广方案如何写
前驱节点(predecessor) 前驱节点:中序遍历时的前一个节点。如果是二叉搜索树,前驱节点就是前一个比它小的节点。 node.left ! null 举例:6、13、8predecessor node.left.right.right.right...,终止条件&a…...