Program.cs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. using Microsoft.Win32;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Security.Principal;
  6. using System.Threading.Tasks;
  7. using System.Windows.Forms;
  8. namespace UAS_XmlAnalysor
  9. {
  10. static class Program
  11. {
  12. /// <summary>
  13. /// 应用程序的主入口点。
  14. /// </summary>
  15. [STAThread]
  16. static void Main()
  17. {
  18. try
  19. {
  20. WindowsIdentity identity = WindowsIdentity.GetCurrent();
  21. WindowsPrincipal principal = new WindowsPrincipal(identity);
  22. Application.EnableVisualStyles();
  23. Application.SetCompatibleTextRenderingDefault(false);
  24. if (principal.IsInRole(WindowsBuiltInRole.Administrator))
  25. Application.Run(new Form1());
  26. else
  27. {
  28. //创建启动对象
  29. System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
  30. // 设置运行文件
  31. startInfo.FileName = Application.ExecutablePath;
  32. //设置启动动作,确保以管理员身份运行
  33. startInfo.Verb = "runas";
  34. //如果不是管理员,则启动UAC
  35. System.Diagnostics.Process.Start(startInfo);
  36. }
  37. }
  38. catch (Exception)
  39. {
  40. }
  41. }
  42. public static void SetAutoRun(string fileName, bool isAutoRun)
  43. {
  44. RegistryKey reg = null;
  45. try
  46. {
  47. if (!System.IO.File.Exists(fileName))
  48. throw new Exception("该文件不存在!");
  49. string name = fileName.Substring(fileName.LastIndexOf(@"\") + 1);
  50. reg = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", true);
  51. if (reg == null)
  52. reg = Registry.LocalMachine.CreateSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run");
  53. if (isAutoRun)
  54. reg.SetValue(name, fileName);
  55. else
  56. reg.SetValue(name, false);
  57. }
  58. catch (Exception ex)
  59. {
  60. throw new Exception(ex.ToString());
  61. }
  62. finally
  63. {
  64. if (reg != null)
  65. reg.Close();
  66. }
  67. }
  68. }
  69. }