MainWindow.xaml.cs 65 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Runtime.InteropServices;
  5. using System.Text;
  6. using System.Windows;
  7. using System.Windows.Controls;
  8. using System.Windows.Data;
  9. using System.Windows.Documents;
  10. using System.Windows.Input;
  11. using System.Windows.Media;
  12. using System.Windows.Media.Imaging;
  13. using System.Windows.Navigation;
  14. using System.Windows.Shapes;
  15. using OSVersionInfoClass;
  16. using Newtonsoft.Json;
  17. using Newtonsoft.Json.Linq;
  18. using System.Net;
  19. using System.IO;
  20. using System.Threading;
  21. using Microsoft.Win32;
  22. using CmwtatDigital.Domain;
  23. using System.Text.RegularExpressions;
  24. using System.Windows.Forms;
  25. using System.Globalization;
  26. using System.Reflection;
  27. using MaterialDesignThemes.Wpf;
  28. namespace CmwtatDigital
  29. {
  30. static class Constants
  31. {
  32. public const string DefaultLang = "en"; // 缺省语言
  33. }
  34. /// <summary>
  35. /// MainWindow.xaml 的交互逻辑
  36. /// </summary>
  37. public partial class MainWindow : Window
  38. {
  39. [DllImport("Kernel32.dll")]
  40. private static extern bool Wow64EnableWow64FsRedirection(bool Wow64FsEnableRedirection);//重定向
  41. public struct Frequency
  42. {
  43. public int ID { get; set; }
  44. public string DisplayOS { get; set; }
  45. }
  46. public static void ConsoleLog(string log_text = "")
  47. {
  48. Console.WriteLine(log_text);
  49. if (Program.log2file == true)
  50. {
  51. WriteLog(log_text);
  52. }
  53. }
  54. public static void WriteLog(string strLog)
  55. {
  56. string sFilePath = AppDomain.CurrentDomain.BaseDirectory;
  57. string sFileName = "CMWTAT-" + DateTime.Now.ToString("yyyy-MM-dd") + ".log";
  58. sFileName = sFilePath + sFileName; //文件的绝对路径
  59. if (!Directory.Exists(sFilePath))//验证路径是否存在
  60. {
  61. Directory.CreateDirectory(sFilePath);
  62. //不存在则创建
  63. }
  64. FileStream fs;
  65. StreamWriter sw;
  66. if (File.Exists(sFileName))
  67. //验证文件是否存在,有则追加,无则创建
  68. {
  69. fs = new FileStream(sFileName, FileMode.Append, FileAccess.Write);
  70. }
  71. else
  72. {
  73. fs = new FileStream(sFileName, FileMode.Create, FileAccess.Write);
  74. }
  75. sw = new StreamWriter(fs);
  76. sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss") + " --- " + strLog);
  77. sw.Close();
  78. fs.Close();
  79. }
  80. string tempfile = System.IO.Path.GetTempPath() + @"CmwtatDigital\";
  81. public void DelectTempFile()
  82. {
  83. if (Directory.Exists(tempfile))
  84. {
  85. try
  86. {
  87. FileAttributes attr = File.GetAttributes(tempfile);
  88. if (attr == FileAttributes.Directory)
  89. {
  90. Directory.Delete(tempfile, true);
  91. }
  92. else
  93. {
  94. File.Delete(tempfile);
  95. }
  96. }
  97. catch (Exception e)
  98. {
  99. ConsoleLog("DelectTempFile:" + e.Message);
  100. }
  101. }
  102. }
  103. public void ExportTempFile()
  104. {
  105. if (Directory.Exists(tempfile))
  106. {
  107. ConsoleLog("找到已存在的缓存,开始删除");
  108. DelectTempFile();
  109. ConsoleLog("删除操作完毕");
  110. if (Directory.Exists(tempfile))
  111. {
  112. ConsoleLog("[警告] 检测到文件依旧存在");
  113. }
  114. }
  115. ConsoleLog("开始创建缓存目录");
  116. if (Directory.Exists(tempfile) == false)
  117. {
  118. Directory.CreateDirectory(tempfile);
  119. }
  120. ConsoleLog("创建缓存目录完毕");
  121. ConsoleLog("开始写入缓存文件");
  122. File.WriteAllBytes(tempfile + "ClipUp" + ".exe", Properties.Resources.ClipUp);
  123. //File.WriteAllBytes(tempfile + "LibHWIDx86" + ".dll", Properties.Resources.LibHWIDx86);
  124. //File.WriteAllBytes(tempfile + "LibHWIDx64" + ".dll", Properties.Resources.LibHWIDx64);
  125. File.WriteAllBytes(tempfile + "slmgr" + ".vbs", Properties.Resources.slmgr);
  126. ConsoleLog("写入缓存文件完毕");
  127. }
  128. public static string LocalLang = Constants.DefaultLang;
  129. public static string NowLang = LocalLang;
  130. ResourceDictionary langRd = null; //语言资源字典
  131. public static CultureInfo currentCultureInfo = CultureInfo.CurrentCulture; //获取系统语言
  132. public static bool NotSupportLang = false;
  133. /// <summary>
  134. /// 加载指定语言(支持热加载)
  135. /// </summary>
  136. public void LoadLang(string LangName = Constants.DefaultLang)
  137. {
  138. //MessageBox.Show(currentCultureInfo.Name);
  139. try
  140. {
  141. //根据名字载入语言文件
  142. langRd = System.Windows.Application.LoadComponent(new Uri(@"Lang\" + LangName + ".xaml", UriKind.Relative)) as ResourceDictionary;
  143. NowLang = LangName;
  144. if (LangName != Constants.DefaultLang)
  145. {
  146. LocalLang = LangName;
  147. //btnChangeLang.Tag = LocalLang;
  148. }
  149. NotSupportLang = false;
  150. }
  151. catch
  152. {
  153. NotSupportLang = true;
  154. //System.Windows.MessageBox.Show("The " + LangName + " language pack was not found and the language was set to English.\nIf you want to use Chinese as the interface language, click the \"Language\" button to switch.");
  155. langRd = System.Windows.Application.LoadComponent(new Uri(@"Lang\" + Constants.DefaultLang + ".xaml", UriKind.Relative)) as ResourceDictionary;
  156. NowLang = Constants.DefaultLang;
  157. }
  158. if (langRd != null)
  159. {
  160. //如果已使用其他语言,先清空
  161. if (this.Resources.MergedDictionaries.Count > 0)
  162. {
  163. this.Resources.MergedDictionaries.Clear();
  164. }
  165. this.Resources.MergedDictionaries.Add(langRd);
  166. }
  167. }
  168. private static void ApplyBase(bool isDark)
  169. {
  170. var theme = new PaletteHelper().GetTheme();
  171. theme.SetBaseTheme(isDark ? Theme.Dark : Theme.Light);
  172. new PaletteHelper().SetTheme(theme);
  173. }
  174. string ProductVersion = "0.0.0.0"; // 存储程序版本
  175. /// <summary>
  176. /// 获取当前版本
  177. /// </summary>
  178. private void GetEdition()
  179. {
  180. Assembly assembly = Assembly.GetExecutingAssembly();
  181. ConsoleLog("AppAssemblyFullName: " + assembly.FullName);
  182. // 获取程序集元数据
  183. AssemblyCopyrightAttribute copyright = (AssemblyCopyrightAttribute)
  184. AssemblyCopyrightAttribute.GetCustomAttribute(Assembly.GetExecutingAssembly(),
  185. typeof(AssemblyCopyrightAttribute));
  186. AssemblyDescriptionAttribute description = (AssemblyDescriptionAttribute)
  187. AssemblyDescriptionAttribute.GetCustomAttribute(System.Reflection.Assembly.GetExecutingAssembly(),
  188. typeof(AssemblyDescriptionAttribute));
  189. ProductVersion = System.Windows.Forms.Application.ProductVersion;
  190. ConsoleLog("AppDescription: " + description.Description);
  191. ConsoleLog("AppCopyright: " + copyright.Copyright);
  192. ConsoleLog("AppProductVersion: " + System.Windows.Forms.Application.ProductVersion);
  193. }
  194. //static bool autoact = false;
  195. //static bool hiderun = false;
  196. //static bool expact = false;
  197. //static bool log2file = false;
  198. //static bool showhelp = false;
  199. //public string SystemEdition = OSVersionInfo.Name + " " + OSVersionInfo.Edition;
  200. public string SystemEdition = OSVersionInfo.Edition;
  201. bool isDark = false;
  202. string WindowsTheme = "Light";
  203. NotifyIcon notifyIcon;
  204. public void CheckWindowsTheme()
  205. {
  206. var uiSettings = new Windows.UI.ViewManagement.UISettings();
  207. Windows.UI.Color Wcolor = uiSettings.GetColorValue(Windows.UI.ViewManagement.UIColorType.Background);
  208. System.Drawing.Color Scolor = System.Drawing.Color.FromArgb(Wcolor.R, Wcolor.G, Wcolor.B);
  209. float hue = Scolor.GetHue(); // 色调
  210. float saturation = Scolor.GetSaturation(); // 饱和度
  211. float lightness = Scolor.GetBrightness(); // 亮度
  212. if (lightness > 0.75)
  213. {
  214. isDark = false;
  215. WindowsTheme = "Light";
  216. }
  217. else
  218. {
  219. isDark = true;
  220. WindowsTheme = "Dark";
  221. }
  222. //ConsoleLog("Windows Theme Background is: " + Wcolor);
  223. //ConsoleLog("Windows Theme Brightness is: " + lightness);
  224. //ConsoleLog("Windows Theme Mode is: " + WindowsTheme);
  225. }
  226. public MainWindow()
  227. {
  228. CheckWindowsTheme();
  229. ConsoleLog("Windows Theme Mode is: " + WindowsTheme);
  230. GetEdition(); // 获取程序版本
  231. //autoact = Program.autoact;
  232. //hiderun = Program.hiderun;
  233. //expact = Program.expact;
  234. //log2file = Program.log2file;
  235. //showhelp = Program.showhelp;
  236. //MessageBox.Show("A:" + autoact.ToString() + ";H:" + hiderun.ToString());
  237. InitializeComponent();
  238. ApplyBase(isDark);
  239. string LangName = currentCultureInfo.Name;
  240. //根据本地语言来进行本地化
  241. LangName = LangName.Substring(0, LangName.IndexOf("-"));
  242. //LangName = "ja"; // 如需测试语言,请取消注释此行
  243. LoadLang(LangName);
  244. this.Title = this.Title + " V" + ProductVersion; // 初始化语言后为标题增加版本号
  245. //System.Windows.MessageBox.Show((string)this.Resources["HelpText"]);
  246. if (Program.showhelp == true)
  247. {
  248. DialogHelp.IsOpen = true;
  249. }
  250. notifyIcon = new System.Windows.Forms.NotifyIcon(); // 先初始化托盘图标,以方便语言缺省时提示
  251. notifyIcon.Text = (string)this.Resources["notifyIconTitle"]; //托盘图标标题
  252. notifyIcon.Icon = ((System.Drawing.Icon)(CmwtatDigital.Properties.Resources.CMWTAT_ICON));
  253. if ((Program.hiderun == true && Program.autoact == true) || NotSupportLang == true)
  254. {
  255. notifyIcon.Visible = true;
  256. //打开菜单项
  257. //System.Windows.Forms.MenuItem open = new System.Windows.Forms.MenuItem("Open");
  258. //open.Click += new EventHandler((o, e) =>
  259. //{
  260. // this.Show();
  261. //});
  262. //退出菜单项
  263. System.Windows.Forms.MenuItem exit = new System.Windows.Forms.MenuItem("Exit");
  264. exit.Click += new EventHandler(Exit_Button_Click);
  265. //关联托盘控件
  266. System.Windows.Forms.MenuItem[] childen = new System.Windows.Forms.MenuItem[] { exit };
  267. notifyIcon.ContextMenu = new System.Windows.Forms.ContextMenu(childen);
  268. }
  269. if (NotSupportLang == true)
  270. {
  271. int tipShowMilliseconds = 0;
  272. string tipTitle = (string)this.Resources["notifyIconTitle"];
  273. string tipContent = "The language pack \"" + LangName + "\" was not found, language has been automatically switched to English. You can submit this language on GitHub."; // 提示不支持语言提示
  274. ToolTipIcon tipType = ToolTipIcon.None;
  275. notifyIcon.ShowBalloonTip(tipShowMilliseconds, tipTitle, tipContent, tipType);
  276. }
  277. if (Program.hiderun == true && Program.autoact == true)
  278. {
  279. this.Hide();
  280. int tipShowMilliseconds = 0;
  281. string tipTitle = (string)this.Resources["notifyIconTitle"]; //通知气泡标题
  282. string tipContent = (string)this.Resources["Running"]; //提示正在运行
  283. ToolTipIcon tipType = ToolTipIcon.None;
  284. notifyIcon.ShowBalloonTip(tipShowMilliseconds, tipTitle, tipContent, tipType);
  285. }
  286. //初始化动态表单数据绑定
  287. DataContext = new ViewModel();
  288. this.DialogHostGrid.Visibility = Visibility.Visible;
  289. DialogWait.IsOpen = true;
  290. try
  291. {
  292. RegistryKey pRegKey = Registry.LocalMachine;
  293. pRegKey = pRegKey.OpenSubKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion");
  294. SystemEdition = pRegKey.GetValue("EditionID").ToString();
  295. }
  296. catch
  297. {
  298. SystemEdition = OSVersionInfo.Edition;
  299. }
  300. //SystemEditionText.Text = SystemEdition;
  301. Thread loadthread = new Thread(LoadOSList);
  302. loadthread.Start();
  303. CheckWindowsCore();
  304. }
  305. JArray ositems;
  306. int now_os_index = 0;
  307. string checked_os = "unknow";
  308. bool is_auto = true; //是否为自动模式,false为手动
  309. private void InvokeTest()
  310. {
  311. actbtn.Dispatcher.Invoke(new Action(() =>
  312. {
  313. LoadOSList();
  314. }));
  315. }
  316. /// <summary>
  317. /// 检查更新
  318. /// </summary>
  319. private void CheckUpdate()
  320. {
  321. try
  322. {
  323. string check_update_json = GetHttpWebRequest("https://cmwtat.cloudmoe.com/api/check_update?version=" + ProductVersion);
  324. JObject check_update_jsonobj = JObject.Parse(check_update_json);
  325. List<Frequency> check_update_list = new List<Frequency>();
  326. JValue latest_version = (JValue)check_update_jsonobj["latest"];
  327. JValue oldest_version = (JValue)check_update_jsonobj["oldest"];
  328. //System.Windows.MessageBox.Show(latest_version.ToString());
  329. Version CurrentVersion = new Version(ProductVersion);
  330. Version LatestVersion = new Version(latest_version.ToString());
  331. Version AllowedVersion = new Version(oldest_version.ToString());
  332. if (CurrentVersion >= LatestVersion) // 当前版本大于等于最新版本
  333. {
  334. //System.Windows.MessageBox.Show("无需更新");
  335. }
  336. if (CurrentVersion < LatestVersion) // 当前版本小于最新版本
  337. {
  338. actbtn.Dispatcher.Invoke(new Action(() =>
  339. {
  340. if (CurrentVersion < AllowedVersion) // 当前版本小于最低允许版本
  341. {
  342. this.IgnoreUpdate.IsEnabled = false;
  343. //System.Windows.MessageBox.Show("必须更新");
  344. }
  345. else
  346. {
  347. this.IgnoreUpdate.IsEnabled = true;
  348. }
  349. this.DialogUpdateTitle.Text = (string)this.Resources["UpdateTitle"];
  350. this.DialogUpdateText.Text = (string)this.Resources["UpdateText"] + "\r\n" + (string)this.Resources["CurrentVersion"] + ": " + ProductVersion + "\r\n" + (string)this.Resources["LatestVersion"] + ": " + latest_version.ToString();
  351. this.DialogUpdate.IsOpen = true;
  352. }));
  353. //System.Windows.MessageBox.Show("需要更新");
  354. }
  355. }
  356. catch
  357. {
  358. }
  359. }
  360. public static string MainServerDomain = "https://cmwtat.cloudmoe.com"; // 主要服务器
  361. public static string BackupServerDomain = "https://kms.kumo.moe"; // 备用服务器
  362. private void LoadOSList()
  363. {
  364. int is_selected = 0; //是否已经自动选择,0未选择,1普通模式,2实验模式,3离线KMS模式
  365. actbtn.Dispatcher.Invoke(new Action(() =>
  366. {
  367. DialogWait.IsOpen = true;
  368. }));
  369. try
  370. {
  371. string json;
  372. try
  373. {
  374. json = GetHttpWebRequest(MainServerDomain + "/api/digital?list=1&ver=3"); // 主要服务器
  375. }
  376. catch (Exception e)
  377. {
  378. ConsoleLog("MainServer:" + MainServerDomain + " is not working.");
  379. ConsoleLog("Error Message:" + e.Message);
  380. ConsoleLog("Ready to use BackupServer:" + BackupServerDomain);
  381. json = GetHttpWebRequest(BackupServerDomain + "/api/digital?list=1&ver=3"); // 备用服务器
  382. }
  383. JObject jsonobj = JObject.Parse(json);
  384. List<Frequency> list = new List<Frequency>();
  385. Frequency freq = new Frequency();
  386. ositems = (JArray)jsonobj["OS"];
  387. for (int i = 0; i < ositems.Count(); i++)
  388. {
  389. freq.ID = i;
  390. freq.DisplayOS = jsonobj["OS"][i].ToString();
  391. //按照优先级判断,如果已经自动选择则忽略新的
  392. //选择带版本号
  393. if (String.Equals(jsonobj["OS"][i].ToString(), SystemEdition + OSVersionInfo.BuildVersion, StringComparison.CurrentCultureIgnoreCase) && is_selected == 0)//jsonobj["OS"][i].ToString() == SystemEdition + OSVersionInfo.BuildVersion
  394. {
  395. now_os_index = i;
  396. checked_os = SystemEdition + OSVersionInfo.BuildVersion;
  397. is_selected = 1;
  398. }
  399. //选择带版本号Offline-KMS
  400. if (String.Equals(jsonobj["OS"][i].ToString(), "(Offline-KMS) " + SystemEdition + OSVersionInfo.BuildVersion, StringComparison.CurrentCultureIgnoreCase) && is_selected == 0)//旧的方法:jsonobj["OS"][i].ToString() == "(Experimental) " + SystemEdition,新方法忽略大小写并提升效率
  401. {
  402. now_os_index = i;
  403. checked_os = "(Offline-KMS) " + SystemEdition + OSVersionInfo.BuildVersion;
  404. is_selected = 3;
  405. }
  406. //选择不带版本号
  407. if (String.Equals(jsonobj["OS"][i].ToString(), SystemEdition, StringComparison.CurrentCultureIgnoreCase) && is_selected == 0)//jsonobj["OS"][i].ToString() == SystemEdition
  408. {
  409. now_os_index = i;
  410. checked_os = SystemEdition;
  411. is_selected = 1;
  412. }
  413. //选择不带版本号Offline-KMS
  414. if (String.Equals(jsonobj["OS"][i].ToString(), "(Offline-KMS) " + SystemEdition, StringComparison.CurrentCultureIgnoreCase) && is_selected == 0)//旧的方法:jsonobj["OS"][i].ToString() == "(Experimental) " + SystemEdition,新方法忽略大小写并提升效率
  415. {
  416. now_os_index = i;
  417. checked_os = "(Offline-KMS) " + SystemEdition;
  418. is_selected = 3;
  419. }
  420. //选择不带版本号实验
  421. if (String.Equals(jsonobj["OS"][i].ToString(), "(Experimental) " + SystemEdition, StringComparison.CurrentCultureIgnoreCase) && is_selected == 0)//旧的方法:jsonobj["OS"][i].ToString() == "(Experimental) " + SystemEdition,新方法忽略大小写并提升效率
  422. {
  423. now_os_index = i;
  424. checked_os = "(Experimental) " + SystemEdition;
  425. is_selected = 2;
  426. }
  427. list.Add(freq);
  428. }
  429. actbtn.Dispatcher.Invoke(new Action(() =>
  430. {
  431. this.SystemEditionText.ItemsSource = list;//控件的ID
  432. if (is_selected == 0)//没有匹配
  433. {
  434. this.SystemEditionText.SelectedIndex = 0;
  435. this.DialogWithOKToCloseDialogTitle.Text = (string)this.Resources["Attention"];
  436. this.DialogWithOKToCloseDialogText.Text = (string)this.Resources["May_be_not_be_supported"] + "\r\n(" + (string)this.Resources["System_Edition"] + ": " + SystemEdition + OSVersionInfo.BuildVersion + ")";
  437. this.DialogWithOKToCloseDialog.IsOpen = true;
  438. }
  439. else if (is_selected == 2)//只找到实验性
  440. {
  441. this.SystemEditionText.SelectedIndex = now_os_index;
  442. this.DialogWithOKToCloseDialogTitle.Text = (string)this.Resources["Attention"];
  443. this.DialogWithOKToCloseDialogText.Text = (string)this.Resources["Only_find_experimental"] + "\r\n(" + (string)this.Resources["System_Edition"] + ": " + SystemEdition + OSVersionInfo.BuildVersion + ")";
  444. this.DialogWithOKToCloseDialog.IsOpen = true;
  445. }
  446. else if (is_selected == 3)//只找到长期KMS
  447. {
  448. this.SystemEditionText.SelectedIndex = now_os_index;
  449. this.DialogWithOKToCloseDialogTitle.Text = (string)this.Resources["Attention"];
  450. this.DialogWithOKToCloseDialogText.Text = (string)this.Resources["Only_find_ltok"] + "\r\n(" + (string)this.Resources["System_Edition"] + ": " + SystemEdition + OSVersionInfo.BuildVersion + ")";
  451. this.DialogWithOKToCloseDialog.IsOpen = true;
  452. }
  453. else
  454. {
  455. this.SystemEditionText.SelectedIndex = now_os_index;
  456. }
  457. }));
  458. //this.SystemEditionText.SelectedIndex = now_os_index;
  459. actbtn.Dispatcher.Invoke(new Action(() =>
  460. {
  461. DialogWait.IsOpen = false;
  462. }));
  463. if (Program.autoact == true)//自动激活
  464. {
  465. Thread actthread = new Thread(RunAct);
  466. switch (is_selected)
  467. {
  468. case 1: //正常
  469. actthread.Start();
  470. break;
  471. case 2: //实验性
  472. if (Program.expact == true)
  473. {
  474. actbtn.Dispatcher.Invoke(new Action(() =>
  475. {
  476. DialogWithOKToCloseDialog.IsOpen = false;
  477. }));
  478. actthread.Start();
  479. }
  480. else
  481. {
  482. if (Program.hiderun == true)
  483. {
  484. int tipShowMilliseconds = 0;
  485. string tipTitle = (string)this.Resources["notifyIconTitle"];
  486. string tipContent = (string)this.Resources["notify_May_be_not_be_supported_try"]; //提示不支持可尝试实验性
  487. ToolTipIcon tipType = ToolTipIcon.None;
  488. notifyIcon.ShowBalloonTip(tipShowMilliseconds, tipTitle, tipContent, tipType);
  489. Exit_Button_Click(null, null);//退出
  490. }
  491. }
  492. break;
  493. default:
  494. if (Program.hiderun == true)
  495. {
  496. int tipShowMilliseconds = 0;
  497. string tipTitle = (string)this.Resources["notifyIconTitle"];
  498. string tipContent = (string)this.Resources["notify_May_be_not_be_supported_exit"]; //提示不支持并退出(实验性开启)
  499. ToolTipIcon tipType = ToolTipIcon.None;
  500. notifyIcon.ShowBalloonTip(tipShowMilliseconds, tipTitle, tipContent, tipType);
  501. Exit_Button_Click(null, null);//退出
  502. }
  503. break;
  504. }
  505. }
  506. }
  507. catch
  508. {
  509. actbtn.Dispatcher.Invoke(new Action(() =>
  510. {
  511. DialogWait.IsOpen = false;
  512. }));
  513. actbtn.Dispatcher.Invoke(new Action(() =>
  514. {
  515. DialogWithExit.IsOpen = true;
  516. }));
  517. if (Program.hiderun == true && Program.autoact == true)
  518. {
  519. int tipShowMilliseconds = 0;
  520. string tipTitle = (string)this.Resources["notifyIconTitle"];
  521. string tipContent = (string)this.Resources["notify_Disconnect_to_server_exit"]; //提示无法连接服务器退出
  522. ToolTipIcon tipType = ToolTipIcon.None;
  523. notifyIcon.ShowBalloonTip(tipShowMilliseconds, tipTitle, tipContent, tipType);
  524. Exit_Button_Click(null, null);//退出
  525. }
  526. }
  527. CheckUpdate(); // 检查更新
  528. }
  529. private void CheckWindowsCore()
  530. {
  531. if (SystemEdition.ToLower().IndexOf("core") == -1)
  532. {
  533. upgradefullbtn.IsEnabled = false;
  534. upgradefullbtn.Visibility = Visibility.Collapsed;
  535. this.Height -= 95;
  536. }
  537. }
  538. private void Activate_Button_Click(object sender, RoutedEventArgs e)
  539. {
  540. Thread actthread = new Thread(RunAct);
  541. actthread.Start();
  542. //RunAct();
  543. //LoadOSList();
  544. //MessageBox.Show(json);
  545. //MessageBox.Show(rss["OS"][0].ToString());
  546. //MessageBox.Show(SystemEdition);
  547. }
  548. private void installbtn_Click(object sender, RoutedEventArgs e)
  549. {
  550. Thread installthread = new Thread(RunInstall);
  551. installthread.Start();
  552. }
  553. private void upgradefullbtn_Click(object sender, RoutedEventArgs e)
  554. {
  555. this.DialogUpgradeFullVersion.IsOpen = true;
  556. }
  557. private void UpgradeFullVersionWindows_Click(object sender, RoutedEventArgs e)
  558. {
  559. this.DialogUpgradeFullVersion.IsOpen = false;
  560. Thread upgradethread = new Thread(RunUpgradeFullVersion);
  561. upgradethread.Start();
  562. }
  563. private string GetHttpWebRequest(string url, int timeout = 10000, int retry = 2)
  564. {
  565. string outex = "UnknowError";
  566. for (int i = 0; i < retry; i++) // 默认重试2次
  567. {
  568. ConsoleLog("GetHttpWebRequest Try: " + i.ToString());
  569. try
  570. {
  571. Uri uri = new Uri(url);
  572. HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(uri);
  573. myReq.UserAgent = "User-Agent:Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705";
  574. myReq.Accept = "*/*";
  575. myReq.KeepAlive = true;
  576. myReq.Headers.Add("Accept-Language", "zh-cn,en-us;q=0.5");
  577. myReq.Timeout = timeout; // 默认10s超时
  578. HttpWebResponse result = null;
  579. string strHTML = null;
  580. result = (HttpWebResponse)myReq.GetResponse();
  581. Stream receviceStream = result.GetResponseStream();
  582. StreamReader readerOfStream = new StreamReader(receviceStream, System.Text.Encoding.GetEncoding("utf-8"));
  583. strHTML = readerOfStream.ReadToEnd();
  584. readerOfStream.Close();
  585. receviceStream.Close();
  586. result.Close();
  587. return strHTML;
  588. }
  589. catch (WebException ex)
  590. {
  591. outex = ex.Message;
  592. ConsoleLog("GetHttpWebRequest Exception: " + ex.Message);
  593. if (ex.Status == WebExceptionStatus.Timeout) // 超时重试
  594. {
  595. continue;
  596. }
  597. throw new Exception(ex.Message); // 其他错误抛出
  598. }
  599. }
  600. throw new Exception(outex);
  601. }
  602. private void Exit_Button_Click(object sender, EventArgs e)
  603. {
  604. DelectTempFile();
  605. notifyIcon.Visible = false;
  606. System.Windows.Application.Current.Shutdown();
  607. }
  608. private void RunInstall()
  609. {
  610. ExportTempFile();
  611. //释放文件
  612. actbtn.Dispatcher.Invoke(new Action(() =>
  613. {
  614. this.DialogActProg.IsOpen = true;
  615. this.activatingtext.Text = (string)this.Resources["RunInstall_Converting"]; //提示转换中
  616. }));
  617. Wow64EnableWow64FsRedirection(false);//关闭文件重定向
  618. string code = "-0";
  619. string key = "00000-00000-00000-00000-00000";
  620. string sku = "0";
  621. string msg = "Unknow Error!";
  622. string system = "";
  623. string slmgr = Environment.GetFolderPath(Environment.SpecialFolder.SystemX86) + "\\slmgr.vbs";
  624. string slmgr_self = tempfile + "slmgr.vbs";
  625. try
  626. {
  627. string sourceFile = slmgr;
  628. string targetFile = slmgr_self;
  629. bool isrewrite = true; // true=覆盖已存在的同名文件,false则反之
  630. ConsoleLog("Copy Start: " + sourceFile + " To " + targetFile);
  631. System.IO.File.Copy(sourceFile, targetFile, isrewrite);
  632. ConsoleLog("Copy Completed.");
  633. }
  634. catch (Exception CopyExc)
  635. {
  636. ConsoleLog("Copy has Exception: " + CopyExc.Message);
  637. }
  638. //旧的位置
  639. //string slmgr_self = System.AppDomain.CurrentDomain.BaseDirectory + "slmgr.vbs";
  640. string changepk = Environment.SystemDirectory + "\\changepk.exe";
  641. if (is_auto == true)
  642. {
  643. actbtn.Dispatcher.Invoke(new Action(() =>
  644. {
  645. system = this.SystemEditionText.Text;
  646. }));
  647. actbtn.Dispatcher.Invoke(new Action(() =>
  648. {
  649. this.activatingtext.Text = (string)this.Resources["RunInstall_Getting_Key"]; //提示正在获取密钥
  650. }));
  651. //获取密钥和SKU
  652. try
  653. {
  654. string json;
  655. try
  656. {
  657. json = GetHttpWebRequest(MainServerDomain + "/api/digital?list=0&ver=3"); // 主要服务器
  658. }
  659. catch (Exception e)
  660. {
  661. ConsoleLog("MainServer:" + MainServerDomain + " is not working.");
  662. ConsoleLog("Error Message:" + e.Message);
  663. ConsoleLog("Ready to use BackupServer:" + BackupServerDomain);
  664. json = GetHttpWebRequest(BackupServerDomain + "/api/digital?list=0&ver=3"); // 备用服务器
  665. }
  666. JObject jsonobj = JObject.Parse(json);
  667. List<Frequency> list = new List<Frequency>();
  668. ositems = (JArray)jsonobj["OS"];
  669. key = jsonobj[system]["key"].ToString();
  670. sku = jsonobj[system]["sku"].ToString();
  671. ConsoleLog("Edition:" + system + "\r\nKEY:" + key + "\r\nSKU:" + sku);
  672. }
  673. catch
  674. {
  675. code = "-0";
  676. msg = (string)this.Resources["ErrorMsg-0"]; // "激活Windows10需要网络获取产品密钥 :) \nActivate Windows 10 requires a network to gets the product key :)";
  677. goto EndLine;
  678. }
  679. }
  680. else
  681. {
  682. //手动密钥
  683. actbtn.Dispatcher.Invoke(new Action(() =>
  684. {
  685. key = this.SystemEditionTextInput.Text;
  686. }));
  687. }
  688. actbtn.Dispatcher.Invoke(new Action(() =>
  689. {
  690. this.activatingtext.Text = (string)this.Resources["RunInstall_Uninstalling_old_Key"]; //提示正在卸载旧密钥
  691. }));
  692. //卸载
  693. string runend = RunCScript(slmgr_self, "-upk").Trim();
  694. //string runend = RunCMD(@"cscript.exe /nologo %systemroot%\system32\slmgr.vbs -upk").Trim();
  695. ConsoleLog(runend);
  696. if (runend.EndsWith("successfully.") || runend.EndsWith("not found."))
  697. {
  698. actbtn.Dispatcher.Invoke(new Action(() =>
  699. {
  700. this.activatingtext.Text = (string)this.Resources["RunInstall_Installing_Key"]; //提示正在安装密钥
  701. }));
  702. //安装数字权利升级密钥
  703. if (RunCScript(slmgr_self, "-ipk " + key).Trim().EndsWith("successfully."))
  704. //if (RunCMD(@"cscript.exe /nologo %systemroot%\system32\slmgr.vbs -ipk " + key).Trim().EndsWith("successfully."))
  705. {
  706. code = "200";
  707. }
  708. else
  709. {
  710. code = "-2";
  711. msg = (string)this.Resources["ErrorMsg-2"]; // "无法安装密钥,可能没有选择或输入正确的版本 :(\nCannot to install key, may be you choose or enter a incorrect version. :(";
  712. }
  713. }
  714. else
  715. {
  716. code = "-1";
  717. msg = (string)this.Resources["ErrorMsg-1"]; // "无法卸载旧密钥 :(\nCannot to uninstall old key. :(";
  718. }
  719. //string runend = RunCScript(slmgr_self, "-upk").Trim();
  720. EndLine:;
  721. if (code != "200")
  722. {
  723. actbtn.Dispatcher.Invoke(new Action(() =>
  724. {
  725. this.DialogActProg.IsOpen = false;
  726. this.activatingtext.Text = (string)this.Resources["RunInstall_Converting"]; //提示转换中
  727. this.DialogWithOKToCloseDialog.IsOpen = true;
  728. this.DialogWithOKToCloseDialogTitle.Text = (string)this.Resources["ErrorTitle"]; //错误标题
  729. this.DialogWithOKToCloseDialogText.Text = msg + "\r\n" + (string)this.Resources["ErrorCode"] + code; //错误代码 如:错误信息\r\nCode:000
  730. }));
  731. //MessageBox.Show(msg + "\r\nCode:" + code);
  732. }
  733. else
  734. {
  735. actbtn.Dispatcher.Invoke(new Action(() =>
  736. {
  737. this.DialogActProg.IsOpen = false;
  738. this.activatingtext.Text = (string)this.Resources["RunInstall_Converting"]; //提示转换中
  739. this.DialogWithOKToCloseDialogDonate.IsOpen = true;
  740. this.DialogWithOKToCloseDialogDonateTitle.Text = (string)this.Resources["CompleteTitle"]; //完成标题
  741. this.DialogWithOKToCloseDialogDonateText.Text = (string)this.Resources["DonateTextConverted"]; //完成转换内容
  742. }));
  743. //MessageBox.Show("Congratulation!");
  744. }
  745. DelectTempFile();
  746. //清理文件
  747. }
  748. private void RunUpgradeFullVersion()
  749. {
  750. actbtn.Dispatcher.Invoke(new Action(() =>
  751. {
  752. this.DialogActProg.IsOpen = true;
  753. this.activatingtext.Text = (string)this.Resources["RunUpgradeFullVersion_Upgrading"]; //提示升级中
  754. }));
  755. RunCMD(@"sc start sppsvc");
  756. RunCMD(@"sc start wuauserv");
  757. RunCLI("ChangePK.exe", ".", "/ProductKey VK7JG-NPHTM-C97JM-9MPGT-3V66T"); // Pro
  758. RunCLI("ChangePK.exe", ".", "/ProductKey 2B87N-8KFHP-DKV6R-Y2C8J-PKCKT"); // Pro N
  759. RunCLI("ChangePK.exe", ".", "/ProductKey W269N-WFGWX-YVC9B-4J6C9-T83GX"); // KMS Pro
  760. RunCLI("ChangePK.exe", ".", "/ProductKey MH37W-N47XK-V7XM9-C7227-GCQG9"); // KMS Pro N
  761. actbtn.Dispatcher.Invoke(new Action(() =>
  762. {
  763. this.DialogActProg.IsOpen = false;
  764. }));
  765. }
  766. private void ShowBallSameDig()
  767. {
  768. actbtn.Dispatcher.Invoke(new Action(() =>
  769. {
  770. if (Program.hiderun == true && Program.autoact == true)
  771. {
  772. int tipShowMilliseconds = 0;
  773. string tipTitle = (string)this.Resources["notifyIconTitle"];
  774. string tipContent = this.activatingtext.Text;
  775. ToolTipIcon tipType = ToolTipIcon.None;
  776. notifyIcon.ShowBalloonTip(tipShowMilliseconds, tipTitle, tipContent, tipType);
  777. }
  778. }));
  779. }
  780. private void RunAct()
  781. {
  782. bool is_not_network_to_act = false; //是否无法联网稍后激活
  783. ExportTempFile();
  784. //释放文件
  785. actbtn.Dispatcher.Invoke(new Action(() =>
  786. {
  787. this.DialogActProg.IsOpen = true;
  788. this.activatingtext.Text = (string)this.Resources["RunAct_Activating"]; //提示激活中
  789. ShowBallSameDig();
  790. }));
  791. Wow64EnableWow64FsRedirection(false);//关闭文件重定向
  792. string code = "-0";
  793. string key = "00000-00000-00000-00000-00000";
  794. string sku = "0";
  795. string msg = "Unknow Error!";
  796. string system = "";
  797. string mode = "1"; //1:普通(SYS、SKU、KEY完全);2.需要获取SKU(SYS、KEY);3.手动输入KEY;4.普通OfflineKMS(SYS、SKU、KEY完全)
  798. string slmgr = Environment.GetFolderPath(Environment.SpecialFolder.SystemX86) + "\\slmgr.vbs";
  799. string slmgr_self = tempfile + "slmgr.vbs";
  800. try
  801. {
  802. string sourceFile = slmgr;
  803. string targetFile = slmgr_self;
  804. bool isrewrite = true; // true=覆盖已存在的同名文件,false则反之
  805. ConsoleLog("Copy Start: " + sourceFile + " To " + targetFile);
  806. System.IO.File.Copy(sourceFile, targetFile, isrewrite);
  807. ConsoleLog("Copy Completed.");
  808. }
  809. catch (Exception CopyExc)
  810. {
  811. ConsoleLog("Copy has Exception: " + CopyExc.Message);
  812. }
  813. //旧的位置
  814. //string slmgr_self = System.AppDomain.CurrentDomain.BaseDirectory + "slmgr.vbs";
  815. string changepk = Environment.SystemDirectory + "\\changepk.exe";
  816. if (is_auto == true)
  817. {
  818. actbtn.Dispatcher.Invoke(new Action(() =>
  819. {
  820. system = this.SystemEditionText.Text;
  821. }));
  822. actbtn.Dispatcher.Invoke(new Action(() =>
  823. {
  824. this.activatingtext.Text = (string)this.Resources["RunAct_Getting_Key"]; //提示正在获取密钥
  825. ShowBallSameDig();
  826. }));
  827. //获取密钥和SKU
  828. try
  829. {
  830. string json;
  831. try
  832. {
  833. json = GetHttpWebRequest(MainServerDomain + "/api/digital?list=0&ver=3"); // 主要服务器
  834. }
  835. catch (Exception e)
  836. {
  837. ConsoleLog("MainServer:" + MainServerDomain + " is not working.");
  838. ConsoleLog("Error Message:" + e.Message);
  839. ConsoleLog("Ready to use BackupServer:" + BackupServerDomain);
  840. json = GetHttpWebRequest(BackupServerDomain + "/api/digital?list=0&ver=3"); // 备用服务器
  841. }
  842. JObject jsonobj = JObject.Parse(json);
  843. List<Frequency> list = new List<Frequency>();
  844. ositems = (JArray)jsonobj["OS"];
  845. key = jsonobj[system]["key"].ToString();
  846. sku = jsonobj[system]["sku"].ToString();
  847. ConsoleLog("Edition:" + system + "\r\nKEY:" + key + "\r\nSKU:" + sku);
  848. string selecos = "";
  849. // 获取当前选择的选择的文本
  850. actbtn.Dispatcher.Invoke(new Action(() =>
  851. {
  852. selecos = SystemEditionText.Text;
  853. }));
  854. ConsoleLog("Selected OS: " + selecos);
  855. if (sku == "unknow")
  856. {
  857. mode = "2";
  858. }
  859. if (selecos.ToUpper().StartsWith("(Offline-KMS)".ToUpper()))
  860. {
  861. ConsoleLog("Switch Mode Offline-KMS");
  862. mode = "4";
  863. }
  864. }
  865. catch
  866. {
  867. code = "-0";
  868. msg = (string)this.Resources["ErrorMsg-0"]; // "激活Windows10需要网络获取产品密钥 :) \nActivate Windows 10 requires a network to gets the product key :)";
  869. goto EndLine;
  870. }
  871. }
  872. else
  873. {
  874. actbtn.Dispatcher.Invoke(new Action(() =>
  875. {
  876. key = this.SystemEditionTextInput.Text;
  877. }));
  878. mode = "3";
  879. sku = "unknow";
  880. }
  881. actbtn.Dispatcher.Invoke(new Action(() =>
  882. {
  883. this.activatingtext.Text = (string)this.Resources["RunAct_Uninstalling_old_Key"]; //提示正在卸载旧密钥
  884. ShowBallSameDig();
  885. }));
  886. //卸载
  887. string runend = RunCScript(slmgr_self, "-upk").Trim();
  888. //string runend = RunCMD(@"cscript.exe /nologo %systemroot%\system32\slmgr.vbs -upk").Trim();
  889. ConsoleLog(runend);
  890. if (runend.EndsWith("successfully.") || runend.EndsWith("not found."))
  891. {
  892. RunCScript(slmgr_self, "-ckms").Trim();
  893. if (mode == "4")
  894. {
  895. //长期KMS
  896. RunCMD(@"sc stop sppsvc");
  897. RunCMD(@"del /F /Q %systemroot%\system32\spp\store\2.0\tokens.dat");
  898. RunCMD(@"del /F /Q %systemroot%\system32\spp\store\2.0\data.dat");
  899. RunCMD(@"del /F /Q %systemroot%\system32\spp\store\2.0\cache\cache.dat");
  900. RunCMD(@"sc start sppsvc");
  901. }
  902. if (sku == "unknow")//if (mode == "2" || mode == "3") //获取SKU
  903. {
  904. actbtn.Dispatcher.Invoke(new Action(() =>
  905. {
  906. this.activatingtext.Text = (string)this.Resources["RunAct_Getting_edition_code_Exp"]; // "Getting edition code (Experimental)";
  907. ShowBallSameDig();
  908. }));
  909. //安装转换密钥
  910. runend = RunCScript(slmgr_self, "-ipk " + key);
  911. //runend = RunCMD(@"cscript.exe /nologo %systemroot%\system32\slmgr.vbs -ipk " + key);
  912. ConsoleLog(slmgr_self + " -ipk " + key);
  913. ConsoleLog(runend);
  914. if (runend.Trim().EndsWith("successfully."))
  915. {
  916. Thread.Sleep(6000); //等待6秒,确保SKU生效
  917. sku = GetSKU(); //获取SKU
  918. if (sku != "Error")
  919. {
  920. actbtn.Dispatcher.Invoke(new Action(() =>
  921. {
  922. this.activatingtext.Text = (string)this.Resources["RunAct_Uninstalling_old_Key_Exp"]; //提示正在卸载旧密钥(实验性)
  923. ShowBallSameDig();
  924. }));
  925. runend = RunCScript(slmgr_self, "-upk").Trim();
  926. //runend = RunCMD(@"cscript.exe /nologo %systemroot%\system32\slmgr.vbs -upk").Trim();
  927. ConsoleLog(runend);
  928. if (runend.EndsWith("successfully.") || runend.EndsWith("not found."))
  929. {
  930. actbtn.Dispatcher.Invoke(new Action(() =>
  931. {
  932. this.activatingtext.Text = (string)this.Resources["RunAct_Prepare_for_the_next_step_Exp"]; // "Prepare for the next step (Experimental)";
  933. ShowBallSameDig();
  934. }));
  935. }
  936. }
  937. else
  938. {
  939. code = "-1.2";
  940. msg = (string)this.Resources["ErrorMsg-1.2"]; // "无法获取版本代号 :(\nCannot to get edition code. :(";
  941. goto EndLine;
  942. }
  943. }
  944. else
  945. {
  946. code = "-1.1";
  947. msg = (string)this.Resources["ErrorMsg-1.1"]; // "无法安装密钥,可能没有选择或输入正确的版本 :(\nCannot to install key, may be you choose or enter a incorrect version. :(";
  948. goto EndLine;
  949. }
  950. }
  951. //写入Win7特征
  952. //ChangePKAction(changepk + " /ProductKey " + key);
  953. if (mode == "4")
  954. {
  955. //长期KMS
  956. ConsoleLog(RunCScript(slmgr_self, "-skms 1.1.45.14:1919").Trim()); // いいよ、来いよ www
  957. //ConsoleLog(RunCMD(@"cscript.exe /nologo %systemroot%\system32\slmgr.vbs -skms 1.1.45.14:1919").Trim()); // いいよ、来いよ www
  958. //if (runend.EndsWith("successfully."))
  959. //{
  960. //}
  961. }
  962. actbtn.Dispatcher.Invoke(new Action(() =>
  963. {
  964. this.activatingtext.Text = (string)this.Resources["RunAct_Installing_Key"]; //提示正在安装密钥
  965. ShowBallSameDig();
  966. }));
  967. //安装数字权利升级密钥
  968. runend = RunCScript(slmgr_self, "-ipk " + key);
  969. //runend = RunCMD(@"cscript.exe /nologo %systemroot%\system32\slmgr.vbs -ipk " + key);
  970. ConsoleLog(slmgr_self + " -ipk " + key);
  971. ConsoleLog(runend);
  972. if (runend.Trim().EndsWith("successfully."))
  973. {
  974. actbtn.Dispatcher.Invoke(new Action(() =>
  975. {
  976. this.activatingtext.Text = (string)this.Resources["RunAct_Getting_free_upgrade_permissions"]; // "Getting free upgrade permissions";
  977. ShowBallSameDig();
  978. }));
  979. //LibGatherOsState.GatherOsState.SetLibHWIDPath(tempfile + "LibHWIDx86.dll", tempfile + "LibHWIDx64.dll");
  980. var licenseType = LibGatherOsState.GatherOsState.LicenseType.Retail;
  981. if (mode == "4")
  982. {
  983. //长期KMS
  984. licenseType = LibGatherOsState.GatherOsState.LicenseType.GVLK;
  985. }
  986. var result = LibGatherOsState.GatherOsState.GenActivateLicenseXML(licenseType);
  987. if (result.state == LibGatherOsState.GatherOsState.ActivateLicenseXMLResultState.OK)
  988. {
  989. File.WriteAllText(tempfile + "GenuineTicket.xml", result.xml, Encoding.UTF8);
  990. ConsoleLog("进入下一步");
  991. int try_max_count = 30;
  992. for (int i = 0; i < try_max_count + 1 && !File.Exists(tempfile + "GenuineTicket.xml"); i++)
  993. {
  994. Thread.Sleep(1000);
  995. ConsoleLog($"检查许可证 重试 {i}/{try_max_count}");
  996. }
  997. }
  998. if (File.Exists(tempfile + "GenuineTicket.xml"))
  999. {
  1000. actbtn.Dispatcher.Invoke(new Action(() =>
  1001. {
  1002. this.activatingtext.Text = (string)this.Resources["RunAct_Getting_digital_license"]; // "Getting digital license";
  1003. ShowBallSameDig();
  1004. }));
  1005. RunCMD(@"sc start wuauserv");
  1006. RunCMD(@"sc start clipsvc");
  1007. RunCMD(@"clipup -v -o -altto " + tempfile);
  1008. RunCMD(@"clipup -v -o -altto " + tempfile.TrimEnd('\\')); // 旧版本系统的 ClipUp 路径不能带最后的反斜杠
  1009. if (OSVersionInfo.BuildVersion >= 20348)
  1010. {
  1011. RunCLI(tempfile + "ClipUp.exe", ".", "-v -o -altto " + tempfile); // 固定版本解决 22H2 后 ARM64 许可证接收问题
  1012. RunCLI(tempfile + "ClipUp.exe", ".", "-v -o -altto " + tempfile.TrimEnd('\\'));
  1013. }
  1014. actbtn.Dispatcher.Invoke(new Action(() =>
  1015. {
  1016. this.activatingtext.Text = (string)this.Resources["RunAct_Activating"]; // 提示激活中
  1017. ShowBallSameDig();
  1018. }));
  1019. int try_max_count = 30;
  1020. for (int i = 0; i < try_max_count + 1 && File.Exists(tempfile + "GenuineTicket.xml"); i++)
  1021. {
  1022. Thread.Sleep(1000);
  1023. ConsoleLog($"应用许可证 重试 {i}/{try_max_count}");
  1024. }
  1025. runend = RunCScript(slmgr_self, "-ato").Trim();
  1026. ConsoleLog(runend);
  1027. if (runend.EndsWith("successfully.") || runend.Contains("0xC004F074") || runend.Contains("0xC004C003")) //0xC004F074 是 KMS38 长期激活会出的提示,Error 0xC004C003: The activation server determined that the specified product key is blocked. 是因为未连接激活服务器,下次连接时会自动激活。
  1028. {
  1029. if (runend.Contains("0xC004C003"))
  1030. {
  1031. is_not_network_to_act = true;
  1032. }
  1033. code = "200";
  1034. }
  1035. else
  1036. {
  1037. code = "-4";
  1038. msg = (string)this.Resources["ErrorMsg-4"] + "\r\n" + (string)this.Resources["SysMsg"] + "\r\n" + runend; // "激活失败 :(\nActivation Failed. :(";
  1039. }
  1040. }
  1041. else
  1042. {
  1043. code = "-3";
  1044. msg = (string)this.Resources["ErrorMsg-3"]; // "执行超时,可能没有选择正确或输入的版本 :(\nTime out, may be you choose or enter a incorrect version. :(";
  1045. }
  1046. }
  1047. else
  1048. {
  1049. code = "-2";
  1050. msg = (string)this.Resources["ErrorMsg-2"]; // "无法安装密钥,可能没有选择或输入正确的版本 :(\nCannot to install key, may be you choose or enter a incorrect version. :(";
  1051. }
  1052. }
  1053. else
  1054. {
  1055. code = "-1";
  1056. msg = (string)this.Resources["ErrorMsg-1"]; // "无法卸载旧密钥 :(\nCannot to uninstall old key. :(";
  1057. }
  1058. //string runend = RunCScript(slmgr_self, "-upk").Trim();
  1059. EndLine:;
  1060. if (code != "200")
  1061. {
  1062. actbtn.Dispatcher.Invoke(new Action(() =>
  1063. {
  1064. this.DialogActProg.IsOpen = false;
  1065. this.activatingtext.Text = (string)this.Resources["RunAct_Activating"]; //提示激活中
  1066. this.DialogWithOKToCloseDialog.IsOpen = true;
  1067. this.DialogWithOKToCloseDialogTitle.Text = (string)this.Resources["ErrorTitle"]; //错误标题
  1068. this.DialogWithOKToCloseDialogText.Text = msg + "\r\n" + (string)this.Resources["ErrorCode"] + code; //错误代码 如:错误信息\r\nCode:000
  1069. if (Program.hiderun == true && Program.autoact == true)
  1070. {
  1071. int tipShowMilliseconds = 0;
  1072. string tipTitle = (string)this.Resources["notifyIconTitle"];
  1073. string tipContent = msg;
  1074. ToolTipIcon tipType = ToolTipIcon.None;
  1075. notifyIcon.ShowBalloonTip(tipShowMilliseconds, tipTitle, tipContent, tipType);
  1076. Exit_Button_Click(null, null);
  1077. }
  1078. }));
  1079. //MessageBox.Show(msg + "\r\nCode:" + code);
  1080. }
  1081. else
  1082. {
  1083. actbtn.Dispatcher.Invoke(new Action(() =>
  1084. {
  1085. this.DialogActProg.IsOpen = false;
  1086. this.activatingtext.Text = (string)this.Resources["RunAct_Activating"]; //提示激活中
  1087. this.DialogWithOKToCloseDialogDonate.IsOpen = true;
  1088. this.DialogWithOKToCloseDialogDonateTitle.Text = (string)this.Resources["CompleteTitle"]; //完成标题
  1089. if (is_not_network_to_act == true)
  1090. {
  1091. this.DialogWithOKToCloseDialogDonateText.Text = (string)this.Resources["DonateTextWillActivated"]; //即将激活内容
  1092. }
  1093. else
  1094. {
  1095. this.DialogWithOKToCloseDialogDonateText.Text = (string)this.Resources["DonateTextActivated"]; //完成激活内容
  1096. }
  1097. if (Program.hiderun == true && Program.autoact == true)
  1098. {
  1099. int tipShowMilliseconds = 0;
  1100. string tipTitle = (string)this.Resources["notifyIconTitle"];
  1101. string tipContent = this.DialogWithOKToCloseDialogDonateText.Text;
  1102. ToolTipIcon tipType = ToolTipIcon.None;
  1103. notifyIcon.ShowBalloonTip(tipShowMilliseconds, tipTitle, tipContent, tipType);
  1104. Exit_Button_Click(null, null);
  1105. }
  1106. }));
  1107. //MessageBox.Show("Congratulation!");
  1108. }
  1109. DelectTempFile();
  1110. //清理文件
  1111. }
  1112. private void RunCMD_old(string var)
  1113. {
  1114. Wow64EnableWow64FsRedirection(false);//关闭文件重定向
  1115. System.Diagnostics.Process p = new System.Diagnostics.Process();
  1116. p.StartInfo.FileName = "cmd.exe";//要执行的程序名称
  1117. p.StartInfo.WorkingDirectory = System.AppDomain.CurrentDomain.BaseDirectory;
  1118. p.StartInfo.UseShellExecute = false;
  1119. p.StartInfo.RedirectStandardInput = true;//可能接受来自调用程序的输入信息
  1120. p.StartInfo.RedirectStandardOutput = true;//由调用程序获取输出信息
  1121. p.StartInfo.CreateNoWindow = true;//不显示程序窗口
  1122. p.Start();//启动程序
  1123. //向CMD窗口发送输入信息:
  1124. p.StandardInput.WriteLine(var);
  1125. ConsoleLog(var);
  1126. //p.WaitForExit();
  1127. ConsoleLog(p.StandardOutput.ReadToEnd().Trim());
  1128. p.Close();
  1129. //Wow64EnableWow64FsRedirection(false);//关闭文件重定向
  1130. //System.Diagnostics.Process.Start(var);
  1131. }
  1132. public static string RunCLI(string path, string wdPath, string var = "")
  1133. {
  1134. ConsoleLog(path + " " + var);
  1135. Wow64EnableWow64FsRedirection(false);//关闭文件重定向
  1136. //执行命令行函数
  1137. try
  1138. {
  1139. System.Diagnostics.Process myProcess = new System.Diagnostics.Process();
  1140. myProcess.StartInfo.FileName = path;//要执行的程序名称
  1141. myProcess.StartInfo.UseShellExecute = false;
  1142. myProcess.StartInfo.RedirectStandardInput = true;//可能接受来自调用程序的输入信息
  1143. myProcess.StartInfo.RedirectStandardOutput = true;//由调用程序获取输出信息
  1144. myProcess.StartInfo.CreateNoWindow = true;//不显示程序窗口
  1145. myProcess.StartInfo.Arguments = var;
  1146. myProcess.StartInfo.WorkingDirectory = wdPath;
  1147. //myProcess.Arguments = "/c chcp 65001 > nul && cmd /c \"" + PHPRuntimePath + "\" \"" + path + "\" " + var;
  1148. //myProcess.Arguments = "/c " & Commands
  1149. //myProcess.StartInfo.StandardOutputEncoding = Encoding.UTF8;
  1150. myProcess.Start();
  1151. myProcess.WaitForExit(60 * 1000);
  1152. StreamReader myStreamReader = myProcess.StandardOutput;
  1153. string myString = myStreamReader.ReadToEnd();
  1154. myProcess.Close();
  1155. ConsoleLog(myString.Trim());
  1156. ConsoleLog("执行完毕");
  1157. return myString.Trim();
  1158. }
  1159. catch
  1160. {
  1161. return "Error";
  1162. }
  1163. }
  1164. public static string RunCMD(string var)
  1165. {
  1166. ConsoleLog(var);
  1167. Wow64EnableWow64FsRedirection(false); //关闭文件重定向
  1168. //执行命令行函数
  1169. try
  1170. {
  1171. System.Diagnostics.Process myProcess = new System.Diagnostics.Process();
  1172. myProcess.StartInfo.FileName = "cmd.exe";//要执行的程序名称
  1173. myProcess.StartInfo.UseShellExecute = false;
  1174. myProcess.StartInfo.RedirectStandardInput = true;//可能接受来自调用程序的输入信息
  1175. myProcess.StartInfo.RedirectStandardOutput = true;//由调用程序获取输出信息
  1176. myProcess.StartInfo.CreateNoWindow = true;//不显示程序窗口
  1177. myProcess.StartInfo.Arguments = "/c chcp 437 > nul && cmd /c \"" + var + "\"";
  1178. //myProcess.Arguments = "/c chcp 65001 > nul && cmd /c \"" + PHPRuntimePath + "\" \"" + path + "\" " + var;
  1179. //myProcess.Arguments = "/c " & Commands
  1180. //myProcess.StartInfo.StandardOutputEncoding = Encoding.UTF8;
  1181. myProcess.Start();
  1182. myProcess.WaitForExit(60 * 1000);
  1183. System.IO.StreamReader myStreamReader = myProcess.StandardOutput;
  1184. string myString = myStreamReader.ReadToEnd();
  1185. myProcess.Close();
  1186. ConsoleLog(myString.Trim());
  1187. return myString.Trim();
  1188. }
  1189. catch
  1190. {
  1191. return "Error";
  1192. }
  1193. }
  1194. public static string RunCScript(string path, string var = "")
  1195. {
  1196. ConsoleLog("CScript" + " " + "//Nologo \"" + path + "\" " + var);
  1197. Wow64EnableWow64FsRedirection(false);//关闭文件重定向
  1198. //执行命令行函数
  1199. try
  1200. {
  1201. System.Diagnostics.Process myProcess = new System.Diagnostics.Process();
  1202. System.Diagnostics.ProcessStartInfo ProcessStartInfo = new System.Diagnostics.ProcessStartInfo("CScript", "//Nologo \"" + path + "\" " + var);
  1203. ProcessStartInfo.UseShellExecute = false;
  1204. ProcessStartInfo.RedirectStandardOutput = true;
  1205. ProcessStartInfo.CreateNoWindow = true;
  1206. //myProcessStartInfo.Arguments = "/c chcp 65001 > nul && cmd /c \"" + PHPRuntimePath + "\" \"" + path + "\" " + var;
  1207. //myProcessStartInfo.Arguments = "/c " & Commands
  1208. ProcessStartInfo.StandardOutputEncoding = Encoding.UTF8;
  1209. myProcess.StartInfo = ProcessStartInfo;
  1210. myProcess.Start();
  1211. myProcess.WaitForExit(60 * 1000);
  1212. System.IO.StreamReader myStreamReader = myProcess.StandardOutput;
  1213. string myString = myStreamReader.ReadToEnd();
  1214. myProcess.Close();
  1215. ConsoleLog(myString.Trim());
  1216. return myString.Trim();
  1217. }
  1218. catch
  1219. {
  1220. return "Error";
  1221. }
  1222. }
  1223. public static string GetSKU()
  1224. {
  1225. ConsoleLog("Geting SKU");
  1226. Wow64EnableWow64FsRedirection(false);//关闭文件重定向
  1227. //执行命令行函数
  1228. try
  1229. {
  1230. System.Diagnostics.Process myProcess = new System.Diagnostics.Process();
  1231. myProcess.StartInfo.FileName = "cmd.exe";//要执行的程序名称
  1232. myProcess.StartInfo.UseShellExecute = false;
  1233. myProcess.StartInfo.RedirectStandardOutput = true;
  1234. myProcess.StartInfo.CreateNoWindow = true;
  1235. myProcess.StartInfo.Arguments = "/c wmic os get OperatingSystemSKU";
  1236. //myProcess.Arguments = "/c chcp 65001 > nul && cmd /c \"" + PHPRuntimePath + "\" \"" + path + "\" " + var;
  1237. //myProcess.Arguments = "/c " & Commands
  1238. myProcess.StartInfo.StandardOutputEncoding = Encoding.UTF8;
  1239. myProcess.Start();
  1240. myProcess.WaitForExit(60 * 1000);
  1241. System.IO.StreamReader myStreamReader = myProcess.StandardOutput;
  1242. string myString = myStreamReader.ReadToEnd();
  1243. myProcess.Close();
  1244. myString = Regex.Replace(myString, @"[^0-9]+", "");
  1245. ConsoleLog("Get SKU:\"" + myString.Trim() + "\"");
  1246. return myString.Trim(); //只保留数字SKU
  1247. }
  1248. catch
  1249. {
  1250. return "Error";
  1251. }
  1252. }
  1253. private void Donate_Button_Click(object sender, RoutedEventArgs e)
  1254. {
  1255. System.Diagnostics.Process.Start("https://cmwtat.cloudmoe.com/donate"); // 打开捐赠页
  1256. this.DialogWithOKToCloseDialogDonate.IsOpen = false;
  1257. }
  1258. string last_key = "";
  1259. private void SystemEditionTextInput_TextChanged(object sender, TextChangedEventArgs e)
  1260. {
  1261. if (SystemEditionTextInput.Text != last_key)
  1262. {
  1263. int selectlen = SystemEditionTextInput.SelectionStart;
  1264. string temp = SystemEditionTextInput.Text;
  1265. temp = Regex.Replace(temp, @"[^a-zA-Z0-9]+", "");//XAML禁用输入法,并替换可能粘贴进的意外字符
  1266. temp = Regex.Replace(temp, @"([a-zA-Z0-9]{5}(?!$))", "$1-");
  1267. //temp = string.Join("-", Regex.Matches(temp, @".....").Cast<Match>().ToList());
  1268. SystemEditionTextInput.Text = temp.ToUpper();
  1269. last_key = SystemEditionTextInput.Text;
  1270. SystemEditionTextInput.SelectionStart = SystemEditionTextInput.Text.Length;
  1271. }
  1272. UpdateInputMatch(); // 更新按钮启用状态
  1273. }
  1274. /// <summary>
  1275. /// 验证产品密钥字符串是否匹配正则表达式描述的规则并更新按钮状态(如果自动模式则启用按钮)
  1276. /// </summary>
  1277. private void UpdateInputMatch()
  1278. {
  1279. //防止初始化前访问null出错
  1280. try
  1281. {
  1282. if (actbtn != null)
  1283. {
  1284. string pattern = @"^[a-zA-Z0-9]{5}-[a-zA-Z0-9]{5}-[a-zA-Z0-9]{5}-[a-zA-Z0-9]{5}-[a-zA-Z0-9]{5}$";
  1285. if (is_auto == false)
  1286. {
  1287. if (CmwtatDigital.Domain.IsSN.IsMatch((SystemEditionTextInput.Text ?? "").ToString(), pattern))
  1288. {
  1289. actbtn.IsEnabled = true;
  1290. installbtn.IsEnabled = true;
  1291. }
  1292. else
  1293. {
  1294. actbtn.IsEnabled = false;
  1295. installbtn.IsEnabled = false;
  1296. }
  1297. }
  1298. else
  1299. {
  1300. actbtn.IsEnabled = true;
  1301. installbtn.IsEnabled = true;
  1302. }
  1303. }
  1304. }
  1305. catch { }
  1306. }
  1307. private void A_RadioButton_Checked(object sender, RoutedEventArgs e)
  1308. {
  1309. SystemEditionText.Visibility = Visibility.Visible;
  1310. SystemEditionTextInput.Visibility = Visibility.Hidden;
  1311. is_auto = true;
  1312. UpdateInputMatch(); // 更新按钮启用状态
  1313. }
  1314. private void M_RadioButton_Checked(object sender, RoutedEventArgs e)
  1315. {
  1316. SystemEditionText.Visibility = Visibility.Hidden;
  1317. SystemEditionTextInput.Visibility = Visibility.Visible;
  1318. is_auto = false;
  1319. UpdateInputMatch(); // 更新按钮启用状态
  1320. }
  1321. private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
  1322. {
  1323. DelectTempFile();
  1324. notifyIcon.Visible = false;
  1325. }
  1326. private void UpdateBtn_Click(object sender, RoutedEventArgs e)
  1327. {
  1328. System.Diagnostics.Process.Start("https://cmwtat.cloudmoe.com"); // 打开官网
  1329. }
  1330. private void Window_Activated(object sender, EventArgs e)
  1331. {
  1332. CheckWindowsTheme();
  1333. ApplyBase(isDark); // 应用颜色
  1334. }
  1335. }
  1336. }