App.xaml.cs 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. using System;
  2. using System.Diagnostics;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Reflection;
  6. using System.Security.Principal;
  7. using System.ServiceProcess;
  8. using System.Windows;
  9. namespace PRSServer
  10. {
  11. /// <summary>
  12. /// Interaction logic for App.xaml
  13. /// </summary>
  14. public partial class App : Application
  15. {
  16. private AdminStartup CheckAdmin()
  17. {
  18. if (!IsRunAsAdmin())
  19. {
  20. var proc = new ProcessStartInfo();
  21. proc.UseShellExecute = true;
  22. proc.WorkingDirectory = Environment.CurrentDirectory;
  23. proc.FileName =
  24. Path.ChangeExtension(Assembly.GetEntryAssembly().Location, "exe"); // Required to change to exe because .NET produces a .dll
  25. proc.Verb = "runas";
  26. try
  27. {
  28. Process.Start(proc);
  29. Shutdown(0);
  30. return AdminStartup.Done;
  31. }
  32. catch (Exception ex)
  33. {
  34. MessageBox.Show("This program must be run as an administrator! \n\n" + ex);
  35. }
  36. return AdminStartup.Cannot;
  37. }
  38. return AdminStartup.Already;
  39. }
  40. private bool IsRunAsAdmin()
  41. {
  42. try
  43. {
  44. var id = WindowsIdentity.GetCurrent();
  45. var principal = new WindowsPrincipal(id);
  46. return principal.IsInRole(WindowsBuiltInRole.Administrator);
  47. }
  48. catch (Exception)
  49. {
  50. return false;
  51. }
  52. }
  53. protected override void OnStartup(StartupEventArgs e)
  54. {
  55. base.OnStartup(e);
  56. if (Environment.UserInteractive)
  57. {
  58. var args = Environment.GetCommandLineArgs();
  59. if (args.Length <= 1)
  60. {
  61. if (CheckAdmin() != AdminStartup.Cannot)
  62. {
  63. var f = new Configuration();
  64. f.ShowDialog();
  65. Shutdown(0);
  66. }
  67. else
  68. {
  69. MessageBox.Show("This program must be run as Admin!");
  70. Shutdown(0);
  71. }
  72. }
  73. else if (args[1].StartsWith("/service="))
  74. {
  75. var c = new Console(args[1].Split('=').Last(), args[1].Split('=').Last(), false);
  76. c.ShowDialog();
  77. Shutdown(0);
  78. }
  79. else
  80. {
  81. Shutdown(0);
  82. }
  83. }
  84. else
  85. {
  86. var args = Environment.GetCommandLineArgs();
  87. var serviceName = "";
  88. if (args.Length > 1 && args[1].StartsWith("/service=")) serviceName = args[1].Split('=').Last();
  89. ServiceBase.Run(new PRSService(serviceName, this));
  90. }
  91. }
  92. // -1 failed
  93. // 0 already admin
  94. // 1 launched admin
  95. private enum AdminStartup
  96. {
  97. Already,
  98. Done,
  99. Cannot
  100. }
  101. }
  102. }