Win32Helper.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  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_Master.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. [Flags]
  93. public enum FileMapProtection : uint
  94. {
  95. PageReadonly = 0x02,
  96. PageReadWrite = 0x04,
  97. PageWriteCopy = 0x08,
  98. PageExecuteRead = 0x20,
  99. PageExecuteReadWrite = 0x40,
  100. SectionCommit = 0x8000000,
  101. SectionImage = 0x1000000,
  102. SectionNoCache = 0x10000000,
  103. SectionReserve = 0x4000000,
  104. }
  105. [Flags]
  106. public enum FileMapAccessType : uint
  107. {
  108. Copy = 0x01,
  109. Write = 0x02,
  110. Read = 0x04,
  111. AllAccess = 0x08,
  112. Execute = 0x20,
  113. }
  114. [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
  115. public static extern bool CreateProcess(string lpApplicationName, string lpCommandLine, ref SECURITY_ATTRIBUTES lpProcessAttributes, ref SECURITY_ATTRIBUTES lpThreadAttributes,
  116. bool bInheritHandles, uint dwCreationFlags, IntPtr lpEnvironment, string lpCurrentDirectory, [In] ref STARTUPINFO lpStartupInfo, out PROCESS_INFORMATION lpProcessInformation);
  117. [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
  118. public static extern uint GetModuleFileName([In] IntPtr hModule, [Out] StringBuilder lpFilename, [In][MarshalAs(UnmanagedType.U4)] int nSize);
  119. [DllImport("kernel32.dll")]
  120. public static extern void ExitProcess(uint uExitCode);
  121. [DllImport("shell32.dll")]
  122. static extern void SHChangeNotify(HChangeNotifyEventID wEventId, HChangeNotifyFlags uFlags, IntPtr dwItem1, IntPtr dwItem2);
  123. [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
  124. public static extern UInt32 WaitForSingleObject(IntPtr hHandle, UInt32 dwMilliseconds);
  125. [DllImport("User32.dll", SetLastError = true, CharSet = CharSet.Auto)]
  126. public static extern uint RegisterWindowMessage(string lpString);
  127. [DllImport("User32.dll", SetLastError = true, CharSet = CharSet.Auto)]
  128. public static extern int PostMessage(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam);
  129. [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
  130. public static extern bool SetEvent(IntPtr hEvent);
  131. [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
  132. public static extern IntPtr CreateFileMapping(IntPtr hFile, IntPtr lpFileMappingAttributes, FileMapProtection flProtect, uint dwMaximumSizeHigh, uint dwMaximumSizeLow, [MarshalAs(UnmanagedType.LPStr)] string lpName);
  133. [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
  134. public static extern IntPtr MapViewOfFileEx(IntPtr hFileMappingObject, FileMapAccessType dwDesiredAccess, uint dwFileOffsetHigh, uint dwFileOffsetLow, UIntPtr dwNumberOfBytesToMap, IntPtr lpBaseAddress);
  135. [DllImport("Kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
  136. public static extern int UnmapViewOfFile(IntPtr lpBaseAddress);
  137. [DllImport("Kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
  138. public static extern bool CloseHandle(IntPtr hObject);
  139. [DllImport("Kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
  140. public static extern IntPtr OpenFileMapping(int dwDesiredAccess, int bInheritHandle, [MarshalAs(UnmanagedType.LPStr)] string lpName);
  141. [DllImport("Kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
  142. public static extern IntPtr CreateEvent(IntPtr lpEventAttributes, bool bManualReset, bool bInitialState, string lpName);
  143. [DllImport("Kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
  144. public static extern IntPtr OpenEvent(uint dwDesiredAccess, bool bInheritHandle, string lpName);
  145. /// <summary>
  146. /// 注册为默认PDF浏览器
  147. /// </summary>
  148. /// <param name="isDefault"></param>
  149. /// <returns></returns>
  150. public static bool RegisterDefaultApp(bool isDefault)
  151. {
  152. bool isWin8OrHigher = false;
  153. if (Environment.OSVersion.Version.Major > 6 || (Environment.OSVersion.Version.Major == 6 && Environment.OSVersion.Version.Minor > 1))
  154. {
  155. isWin8OrHigher = true;
  156. }
  157. try
  158. {
  159. AssemblyName assemblyName = Assembly.GetExecutingAssembly().GetName();
  160. /*********** register APP Path *******************/
  161. RegistryKey appPathKey = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths", true);
  162. if (appPathKey == null)
  163. {
  164. return false;
  165. }
  166. RegistryKey appKey = appPathKey.CreateSubKey(assemblyName.Name + ".exe");
  167. if (appKey != null)
  168. {
  169. appKey.SetValue("", Assembly.GetExecutingAssembly().Location);
  170. appKey.SetValue("Path", Directory.GetParent(assemblyName.FullName).FullName);
  171. appKey.Close();
  172. }
  173. appPathKey.Close();
  174. /*********** register ProgID *******************/
  175. RegistryKey progIdKey = Registry.ClassesRoot.CreateSubKey(assemblyName.Name + ".pdf.1");
  176. if (progIdKey == null)
  177. {
  178. return false;
  179. }
  180. progIdKey.SetValue("", assemblyName.Name);
  181. RegistryKey openKey = progIdKey.CreateSubKey("Shell\\Open\\Command");
  182. openKey.SetValue("", Assembly.GetExecutingAssembly().Location + " \"%s\" \"%1\"");
  183. openKey.Close();
  184. progIdKey.Close();
  185. /*********** register Default File Association *******************/
  186. RegistryKey softwareKey = Registry.LocalMachine.CreateSubKey("Software\\" + assemblyName.Name);
  187. if (softwareKey == null)
  188. {
  189. return false;
  190. }
  191. RegistryKey capabKey = softwareKey.CreateSubKey("Capabilities\\FileAssociations");
  192. capabKey.SetValue(".pdf", assemblyName.Name + ".pdf.1");
  193. capabKey.Close();
  194. capabKey = softwareKey.CreateSubKey("Capabilities", true);
  195. capabKey.SetValue("ApplicationDescription", assemblyName.Name);
  196. capabKey.Close();
  197. softwareKey.Close();
  198. /*********** register Default App List *******************/
  199. RegistryKey regiserAppKeys = Registry.LocalMachine.OpenSubKey("SOFTWARE\\RegisteredApplications", true);
  200. if (regiserAppKeys == null)
  201. {
  202. return false;
  203. }
  204. regiserAppKeys.SetValue(assemblyName.Name, "SOFTWARE\\" + assemblyName.Name + "\\Capabilities");
  205. regiserAppKeys.Close();
  206. Registry.ClassesRoot.SetValue(".pdf", assemblyName.Name + ".pdf.1");
  207. if (isDefault)
  208. {
  209. if (isWin8OrHigher)
  210. {
  211. PROCESS_INFORMATION pInfo = new PROCESS_INFORMATION();
  212. STARTUPINFO sInfo = new STARTUPINFO();
  213. SECURITY_ATTRIBUTES pSec = new SECURITY_ATTRIBUTES();
  214. SECURITY_ATTRIBUTES tSec = new SECURITY_ATTRIBUTES();
  215. pSec.nLength = Marshal.SizeOf(pSec);
  216. tSec.nLength = Marshal.SizeOf(tSec);
  217. string commandLine = " \".pdf\" \"" + assemblyName.Name + ".pdf.1\"";
  218. CreateProcess("Resources\\exe\\SFTA.exe", commandLine, ref pSec, ref tSec, false, 0, IntPtr.Zero, null, ref sInfo, out pInfo);
  219. WaitForSingleObject(pInfo.hProcess, 3000);
  220. }
  221. else
  222. {
  223. RegistryKey defaultKey = Registry.CurrentUser.CreateSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\FileExts\\.pdf\\UserChoice", true);
  224. defaultKey.SetValue("ProgId", assemblyName.Name + ".pdf.1");
  225. defaultKey.Close();
  226. SHChangeNotify(HChangeNotifyEventID.SHCNE_ASSOCCHANGED, HChangeNotifyFlags.SHCNF_IDLIST, IntPtr.Zero, IntPtr.Zero);
  227. }
  228. }
  229. else
  230. {
  231. RegistryKey defaultKey = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\FileExts\\.pdf", true);
  232. RegistryKey userChoice = defaultKey.OpenSubKey("UserChoice");
  233. string checkId = userChoice.GetValue("ProgId").ToString();
  234. if (checkId == (assemblyName.Name + ".pdf.1") || checkId == "PDF Technologies, Inc..PDF Master")
  235. {
  236. defaultKey.DeleteSubKey("UserChoice");
  237. SHChangeNotify(HChangeNotifyEventID.SHCNE_ASSOCCHANGED, HChangeNotifyFlags.SHCNF_IDLIST, IntPtr.Zero, IntPtr.Zero);
  238. }
  239. defaultKey.Close();
  240. }
  241. return true;
  242. }
  243. catch
  244. {
  245. }
  246. return false;
  247. }
  248. /// <summary>
  249. /// 判断是否是默认pdf阅读器
  250. /// </summary>
  251. /// <returns></returns>
  252. public static bool IsDefaultApp()
  253. {
  254. try
  255. {
  256. AssemblyName assemblyName = Assembly.GetExecutingAssembly().GetName();
  257. var asm = Assembly.GetExecutingAssembly();
  258. RegistryKey defaultKey = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\FileExts\\.pdf\\UserChoice");
  259. AssemblyCompanyAttribute asmcpn = (AssemblyCompanyAttribute)Attribute.GetCustomAttribute(asm, typeof(AssemblyCompanyAttribute));
  260. AssemblyProductAttribute aspro = (AssemblyProductAttribute)Attribute.GetCustomAttribute(asm, typeof(AssemblyProductAttribute));
  261. string id = string.Format("{0}.{1}", asmcpn.Company, aspro.Product);
  262. if (defaultKey != null)
  263. {
  264. string checkId = defaultKey.GetValue("ProgId").ToString();
  265. if (checkId == "PDF Technologies, Inc..PDF Reader Pro" || checkId == id)
  266. {
  267. return true;
  268. }
  269. defaultKey.Close();
  270. if (checkId == (assemblyName.Name + ".pdf.1"))
  271. {
  272. return true;
  273. }
  274. }
  275. }
  276. catch { }
  277. return false;
  278. }
  279. /// <summary>
  280. /// 判断当前程序是否以管理员身份运行
  281. /// </summary>
  282. /// <returns></returns>
  283. public static bool IsRunAsAdmin()
  284. {
  285. WindowsIdentity id = WindowsIdentity.GetCurrent();
  286. WindowsPrincipal principal = new WindowsPrincipal(id);
  287. return principal.IsInRole(WindowsBuiltInRole.Administrator);
  288. }
  289. }
  290. }