在windows csharp的程式中,如果要一開始限定執行為administrator系統管理權限,可以在manifest檔註記
參考 https://stackoverflow.com/questions/2818179/how-do-i-force-my-net-application-to-run-as-administrator
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
或是用程式強制重新起始為系統管理權限(放在Main起始處)
參考 https://itneverworksfirsttime.wordpress.com/2012/02/27/using-uac-to-request-administrative-privileges-from-c/
WindowsPrincipal pricipal = new WindowsPrincipal(WindowsIdentity.GetCurrent()); bool hasAdministrativeRight = pricipal.IsInRole(WindowsBuiltInRole.Administrator); if (!hasAdministrativeRight) { // relaunch the application with admin rights string fileName = System.Reflection.Assembly.GetExecutingAssembly().Location; ProcessStartInfo processInfo = new ProcessStartInfo(); processInfo.Verb = "runas"; processInfo.FileName = fileName; try { Process.Start(processInfo); } catch (System.ComponentModel.Win32Exception) { // This will be thrown if the user cancels the prompt } return; }
另外實測時,如果是32bit程式,在某些情況會被windows7判定為安裝程式而跳出”This program might not have installed correctly”
https://docs.microsoft.com/en-us/windows/desktop/SbsCs/application-manifests
可用manifest繞過Program Compatibility Assistant(PCA)
https://support.microsoft.com/en-my/help/2545347/excluding-programs-from-the-program-compatibility-assistant-pca
<compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1"> <application> <!-- Windows Vista and Windows Server 2008 --> <supportedOS Id="{e2011457-1546-43c5-a5fe-008deee3d3f0}"/> <!-- Windows 7 and Windows Server 2008 R2 --> <supportedOS Id="{35138b9a-5d96-4fbd-8e2d-a2440225f93a}"/> <!-- Windows 8 and Windows Server 2012 --> <supportedOS Id="{4a2f28e3-53b9-4441-ba9c-d69d4a4a6e38}"/> <!-- Windows 8.1 and Windows Server 2012 R2 --> <supportedOS Id="{1f676c76-80e1-4239-95bb-83d0f6d0da78}"/> <!-- Windows 10 --> <supportedOS Id="{8e0f7a12-bfb3-4fe8-b9a5-48fd50a15a9a}"/> </application> </compatibility>