Program.cs 2.6 KB

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