Win32Helper.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  1. using Microsoft.Win32;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Reflection;
  7. using System.Runtime.InteropServices;
  8. using System.Security.Principal;
  9. using System.Text;
  10. using System.Threading.Tasks;
  11. namespace PDF_Office.Helper
  12. {
  13. /// <summary>
  14. /// 设置成默认阅读器的辅助类
  15. /// </summary>
  16. public static class Win32Helper
  17. {
  18. [StructLayout(LayoutKind.Sequential)]
  19. public struct SECURITY_ATTRIBUTES
  20. {
  21. public int nLength;
  22. public IntPtr lpSecurityDescriptor;
  23. public int bInheritHandle;
  24. }
  25. [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
  26. public struct STARTUPINFO
  27. {
  28. public Int32 cb;
  29. public string lpReserved;
  30. public string lpDesktop;
  31. public string lpTitle;
  32. public Int32 dwX;
  33. public Int32 dwY;
  34. public Int32 dwXSize;
  35. public Int32 dwYSize;
  36. public Int32 dwXCountChars;
  37. public Int32 dwYCountChars;
  38. public Int32 dwFillAttribute;
  39. public Int32 dwFlags;
  40. public Int16 wShowWindow;
  41. public Int16 cbReserved2;
  42. public IntPtr lpReserved2;
  43. public IntPtr hStdInput;
  44. public IntPtr hStdOutput;
  45. public IntPtr hStdError;
  46. }
  47. [StructLayout(LayoutKind.Sequential)]
  48. public struct PROCESS_INFORMATION
  49. {
  50. public IntPtr hProcess;
  51. public IntPtr hThread;
  52. public int dwProcessId;
  53. public int dwThreadId;
  54. }
  55. [Flags]
  56. public enum HChangeNotifyEventID
  57. {
  58. SHCNE_ALLEVENTS = 0x7FFFFFFF,
  59. SHCNE_ASSOCCHANGED = 0x08000000,
  60. SHCNE_ATTRIBUTES = 0x00000800,
  61. SHCNE_CREATE = 0x00000002,
  62. SHCNE_DELETE = 0x00000004,
  63. SHCNE_DRIVEADD = 0x00000100,
  64. SHCNE_DRIVEADDGUI = 0x00010000,
  65. SHCNE_DRIVEREMOVED = 0x00000080,
  66. SHCNE_EXTENDED_EVENT = 0x04000000,
  67. SHCNE_FREESPACE = 0x00040000,
  68. SHCNE_MEDIAINSERTED = 0x00000020,
  69. SHCNE_MEDIAREMOVED = 0x00000040,
  70. SHCNE_MKDIR = 0x00000008,
  71. SHCNE_NETSHARE = 0x00000200,
  72. SHCNE_NETUNSHARE = 0x00000400,
  73. SHCNE_RENAMEFOLDER = 0x00020000,
  74. SHCNE_RENAMEITEM = 0x00000001,
  75. SHCNE_RMDIR = 0x00000010,
  76. SHCNE_SERVERDISCONNECT = 0x00004000,
  77. SHCNE_UPDATEDIR = 0x00001000,
  78. SHCNE_UPDATEIMAGE = 0x00008000,
  79. }
  80. [Flags]
  81. public enum HChangeNotifyFlags
  82. {
  83. SHCNF_DWORD = 0x0003,
  84. SHCNF_IDLIST = 0x0000,
  85. SHCNF_PATHA = 0x0001,
  86. SHCNF_PATHW = 0x0005,
  87. SHCNF_PRINTERA = 0x0002,
  88. SHCNF_PRINTERW = 0x0006,
  89. SHCNF_FLUSH = 0x1000,
  90. SHCNF_FLUSHNOWAIT = 0x2000
  91. }
  92. [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
  93. public static extern bool CreateProcess(string lpApplicationName, string lpCommandLine, ref SECURITY_ATTRIBUTES lpProcessAttributes, ref SECURITY_ATTRIBUTES lpThreadAttributes,
  94. bool bInheritHandles, uint dwCreationFlags, IntPtr lpEnvironment, string lpCurrentDirectory, [In] ref STARTUPINFO lpStartupInfo, out PROCESS_INFORMATION lpProcessInformation);
  95. [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
  96. public static extern uint GetModuleFileName([In] IntPtr hModule, [Out] StringBuilder lpFilename, [In][MarshalAs(UnmanagedType.U4)] int nSize);
  97. [DllImport("kernel32.dll")]
  98. public static extern void ExitProcess(uint uExitCode);
  99. [DllImport("shell32.dll")]
  100. static extern void SHChangeNotify(HChangeNotifyEventID wEventId, HChangeNotifyFlags uFlags, IntPtr dwItem1, IntPtr dwItem2);
  101. [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
  102. public static extern UInt32 WaitForSingleObject(IntPtr hHandle, UInt32 dwMilliseconds);
  103. /// <summary>
  104. /// 注册为默认PDF浏览器
  105. /// </summary>
  106. /// <param name="isDefault"></param>
  107. /// <returns></returns>
  108. public static bool RegisterDefaultApp(bool isDefault)
  109. {
  110. bool isWin8OrHigher = false;
  111. if (Environment.OSVersion.Version.Major > 6 || (Environment.OSVersion.Version.Major == 6 && Environment.OSVersion.Version.Minor > 1))
  112. {
  113. isWin8OrHigher = true;
  114. }
  115. try
  116. {
  117. AssemblyName assemblyName = Assembly.GetExecutingAssembly().GetName();
  118. /*********** register APP Path *******************/
  119. RegistryKey appPathKey = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths", true);
  120. if (appPathKey == null)
  121. {
  122. return false;
  123. }
  124. RegistryKey appKey = appPathKey.CreateSubKey(assemblyName.Name + ".exe");
  125. if (appKey != null)
  126. {
  127. appKey.SetValue("", Assembly.GetExecutingAssembly().Location);
  128. appKey.SetValue("Path", Directory.GetParent(assemblyName.FullName).FullName);
  129. appKey.Close();
  130. }
  131. appPathKey.Close();
  132. /*********** register ProgID *******************/
  133. RegistryKey progIdKey = Registry.ClassesRoot.CreateSubKey(assemblyName.Name + ".pdf.1");
  134. if (progIdKey == null)
  135. {
  136. return false;
  137. }
  138. progIdKey.SetValue("", assemblyName.Name);
  139. RegistryKey openKey = progIdKey.CreateSubKey("Shell\\Open\\Command");
  140. openKey.SetValue("", Assembly.GetExecutingAssembly().Location + " \"%s\" \"%1\"");
  141. openKey.Close();
  142. progIdKey.Close();
  143. /*********** register Default File Association *******************/
  144. RegistryKey softwareKey = Registry.LocalMachine.CreateSubKey("Software\\" + assemblyName.Name);
  145. if (softwareKey == null)
  146. {
  147. return false;
  148. }
  149. RegistryKey capabKey = softwareKey.CreateSubKey("Capabilities\\FileAssociations");
  150. capabKey.SetValue(".pdf", assemblyName.Name + ".pdf.1");
  151. capabKey.Close();
  152. capabKey = softwareKey.CreateSubKey("Capabilities", true);
  153. capabKey.SetValue("ApplicationDescription", assemblyName.Name);
  154. capabKey.Close();
  155. softwareKey.Close();
  156. /*********** register Default App List *******************/
  157. RegistryKey regiserAppKeys = Registry.LocalMachine.OpenSubKey("SOFTWARE\\RegisteredApplications", true);
  158. if (regiserAppKeys == null)
  159. {
  160. return false;
  161. }
  162. regiserAppKeys.SetValue(assemblyName.Name, "SOFTWARE\\" + assemblyName.Name + "\\Capabilities");
  163. regiserAppKeys.Close();
  164. Registry.ClassesRoot.SetValue(".pdf", assemblyName.Name + ".pdf.1");
  165. if (isDefault)
  166. {
  167. if (isWin8OrHigher)
  168. {
  169. PROCESS_INFORMATION pInfo = new PROCESS_INFORMATION();
  170. STARTUPINFO sInfo = new STARTUPINFO();
  171. SECURITY_ATTRIBUTES pSec = new SECURITY_ATTRIBUTES();
  172. SECURITY_ATTRIBUTES tSec = new SECURITY_ATTRIBUTES();
  173. pSec.nLength = Marshal.SizeOf(pSec);
  174. tSec.nLength = Marshal.SizeOf(tSec);
  175. string commandLine = " \".pdf\" \"" + assemblyName.Name + ".pdf.1\"";
  176. CreateProcess("Resources\\exe\\SFTA.exe", commandLine, ref pSec, ref tSec, false, 0, IntPtr.Zero, null, ref sInfo, out pInfo);
  177. WaitForSingleObject(pInfo.hProcess, 3000);
  178. }
  179. else
  180. {
  181. RegistryKey defaultKey = Registry.CurrentUser.CreateSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\FileExts\\.pdf\\UserChoice", true);
  182. defaultKey.SetValue("ProgId", assemblyName.Name + ".pdf.1");
  183. defaultKey.Close();
  184. SHChangeNotify(HChangeNotifyEventID.SHCNE_ASSOCCHANGED, HChangeNotifyFlags.SHCNF_IDLIST, IntPtr.Zero, IntPtr.Zero);
  185. }
  186. }
  187. else
  188. {
  189. RegistryKey defaultKey = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\FileExts\\.pdf", true);
  190. RegistryKey userChoice = defaultKey.OpenSubKey("UserChoice");
  191. string checkId = userChoice.GetValue("ProgId").ToString();
  192. if (checkId == (assemblyName.Name + ".pdf.1") || checkId == "PDF Technologies, Inc..PDF Reader Pro")
  193. {
  194. defaultKey.DeleteSubKey("UserChoice");
  195. SHChangeNotify(HChangeNotifyEventID.SHCNE_ASSOCCHANGED, HChangeNotifyFlags.SHCNF_IDLIST, IntPtr.Zero, IntPtr.Zero);
  196. }
  197. defaultKey.Close();
  198. }
  199. return true;
  200. }
  201. catch (Exception ex)
  202. {
  203. }
  204. return false;
  205. }
  206. /// <summary>
  207. /// 判断是否是默认pdf阅读器
  208. /// </summary>
  209. /// <returns></returns>
  210. public static bool IsDefaultApp()
  211. {
  212. try
  213. {
  214. AssemblyName assemblyName = Assembly.GetExecutingAssembly().GetName();
  215. var asm = Assembly.GetExecutingAssembly();
  216. RegistryKey defaultKey = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\FileExts\\.pdf\\UserChoice");
  217. AssemblyCompanyAttribute asmcpn = (AssemblyCompanyAttribute)Attribute.GetCustomAttribute(asm, typeof(AssemblyCompanyAttribute));
  218. AssemblyProductAttribute aspro = (AssemblyProductAttribute)Attribute.GetCustomAttribute(asm, typeof(AssemblyProductAttribute));
  219. string id = string.Format("{0}.{1}", asmcpn.Company, aspro.Product);
  220. if (defaultKey != null)
  221. {
  222. string checkId = defaultKey.GetValue("ProgId").ToString();
  223. if (checkId == "PDF Technologies, Inc..PDF Reader Pro" || checkId == id)
  224. {
  225. return true;
  226. }
  227. defaultKey.Close();
  228. if (checkId == (assemblyName.Name + ".pdf.1"))
  229. {
  230. return true;
  231. }
  232. }
  233. }
  234. catch { }
  235. return false;
  236. }
  237. /// <summary>
  238. /// 判断当前程序是否以管理员身份运行
  239. /// </summary>
  240. /// <returns></returns>
  241. public static bool IsRunAsAdmin()
  242. {
  243. WindowsIdentity id = WindowsIdentity.GetCurrent();
  244. WindowsPrincipal principal = new WindowsPrincipal(id);
  245. return principal.IsInRole(WindowsBuiltInRole.Administrator);
  246. }
  247. }
  248. }