PageRenderTime 60ms CodeModel.GetById 26ms RepoModel.GetById 0ms app.codeStats 1ms

/InternetChecker/MainWindow.xaml.cs

https://gitlab.com/Der_Informatiker/InternetChecker
C# | 483 lines | 405 code | 63 blank | 15 comment | 30 complexity | 42873db885fe675dec988edc7e0dab43 MD5 | raw file
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Diagnostics;
  5. using System.IO;
  6. using System.Linq;
  7. using System.Net;
  8. using System.Net.NetworkInformation;
  9. using System.Net.Sockets;
  10. using System.Runtime.InteropServices;
  11. using System.Text;
  12. using System.Threading.Tasks;
  13. using System.Windows;
  14. using System.Windows.Controls;
  15. using System.Windows.Data;
  16. using System.Windows.Documents;
  17. using System.Windows.Input;
  18. using System.Windows.Interop;
  19. using System.Windows.Media;
  20. using System.Windows.Media.Imaging;
  21. using System.Windows.Navigation;
  22. using System.Windows.Shapes;
  23. using System.Windows.Threading;
  24. namespace InternetChecker
  25. {
  26. /// <summary>
  27. /// Interaktionslogik für MainWindow.xaml
  28. /// </summary>
  29. public partial class MainWindow : Window
  30. {
  31. private bool _connected;
  32. private bool _allFunctions;
  33. public DispatcherTimer _monitorUpdateTimer;
  34. public DispatcherTimer _updateTimer;
  35. public MainWindow(bool all)
  36. {
  37. CleanUp();
  38. _allFunctions = all;
  39. InitializeComponent();
  40. Start();
  41. }
  42. #region Window styles
  43. [Flags]
  44. public enum ExtendedWindowStyles
  45. {
  46. // ...
  47. WS_EX_TOOLWINDOW = 0x00000080,
  48. // ...
  49. }
  50. public enum GetWindowLongFields
  51. {
  52. // ...
  53. GWL_EXSTYLE = (-20),
  54. // ...
  55. }
  56. [DllImport("user32.dll")]
  57. public static extern IntPtr GetWindowLong(IntPtr hWnd, int nIndex);
  58. public static IntPtr SetWindowLong(IntPtr hWnd, int nIndex, IntPtr dwNewLong)
  59. {
  60. int error = 0;
  61. IntPtr result = IntPtr.Zero;
  62. // Win32 SetWindowLong doesn't clear error on success
  63. SetLastError(0);
  64. if (IntPtr.Size == 4)
  65. {
  66. // use SetWindowLong
  67. Int32 tempResult = IntSetWindowLong(hWnd, nIndex, IntPtrToInt32(dwNewLong));
  68. error = Marshal.GetLastWin32Error();
  69. result = new IntPtr(tempResult);
  70. }
  71. else
  72. {
  73. // use SetWindowLongPtr
  74. result = IntSetWindowLongPtr(hWnd, nIndex, dwNewLong);
  75. error = Marshal.GetLastWin32Error();
  76. }
  77. if ((result == IntPtr.Zero) && (error != 0))
  78. {
  79. throw new System.ComponentModel.Win32Exception(error);
  80. }
  81. return result;
  82. }
  83. [DllImport("user32.dll", EntryPoint = "SetWindowLongPtr", SetLastError = true)]
  84. private static extern IntPtr IntSetWindowLongPtr(IntPtr hWnd, int nIndex, IntPtr dwNewLong);
  85. [DllImport("user32.dll", EntryPoint = "SetWindowLong", SetLastError = true)]
  86. private static extern Int32 IntSetWindowLong(IntPtr hWnd, int nIndex, Int32 dwNewLong);
  87. private static int IntPtrToInt32(IntPtr intPtr)
  88. {
  89. return unchecked((int)intPtr.ToInt64());
  90. }
  91. [DllImport("kernel32.dll", EntryPoint = "SetLastError")]
  92. public static extern void SetLastError(int dwErrorCode);
  93. #endregion
  94. public void _monitorUpdateTimer_Tick(object sender, EventArgs e)
  95. {
  96. Debug.WriteLine("Monitor-Check");
  97. if (System.Windows.Forms.Screen.AllScreens.Count() != Helper.ScreenCount)
  98. {
  99. System.Windows.Forms.Application.Restart();
  100. Environment.Exit(0);
  101. }
  102. }
  103. public async void Start()
  104. {
  105. Helper.WaitingForUpdate = false;
  106. _connected = false;
  107. if (_allFunctions)
  108. {
  109. _monitorUpdateTimer = new DispatcherTimer();
  110. _monitorUpdateTimer.Tick += _monitorUpdateTimer_Tick;
  111. _monitorUpdateTimer.Interval = new TimeSpan(0, 0, 2);
  112. _monitorUpdateTimer.Start();
  113. _updateTimer = new DispatcherTimer();
  114. _updateTimer.Tick += _updateTimer_Tick;
  115. _updateTimer.Interval = new TimeSpan(0, 5, 0);
  116. _updateTimer.Start();
  117. }
  118. while (true)
  119. {
  120. try
  121. {
  122. CheckConnection();
  123. await Task.Delay(500);
  124. }
  125. catch (Exception/* ex*/)
  126. {
  127. //MessageBox.Show(ex.Message);
  128. //this.Close();
  129. }
  130. finally
  131. {
  132. await Task.Delay(500);
  133. }
  134. }
  135. }
  136. private void _updateTimer_Tick(object sender, EventArgs e)
  137. {
  138. if (!Helper.WaitingForUpdate)
  139. {
  140. CheckForUpdates();
  141. }
  142. else
  143. _updateTimer.Stop();
  144. }
  145. public void CheckConnection()
  146. {
  147. Ping ping = new Ping();
  148. ping.PingCompleted += Ping_PingCompleted;
  149. //ping.SendAsync("www.google.com", 1000, null);
  150. ping.SendAsync("8.8.8.8", 1500, null);
  151. }
  152. private void Ping_PingCompleted(object sender, PingCompletedEventArgs e)
  153. {
  154. if (e.Reply != null)
  155. {
  156. if (e.Reply.Status == IPStatus.Success)
  157. {
  158. if (!_connected)
  159. {
  160. StatusImage.Source = CreateNewImageFromSource("Assets/dot_green.png");
  161. _connected = true;
  162. }
  163. }
  164. else
  165. {
  166. if (_connected)
  167. {
  168. StatusImage.Source = CreateNewImageFromSource("Assets/dot_red.png");
  169. _connected = false;
  170. }
  171. }
  172. }
  173. else
  174. {
  175. if (_connected)
  176. {
  177. StatusImage.Source = CreateNewImageFromSource("Assets/dot_red.png");
  178. _connected = false;
  179. }
  180. }
  181. }
  182. private BitmapImage CreateNewImageFromSource(string imageSource)
  183. {
  184. Image img = new Image();
  185. BitmapImage interimsBitmap = new BitmapImage();
  186. interimsBitmap.BeginInit();
  187. interimsBitmap.UriSource = new Uri(imageSource, UriKind.Relative);
  188. interimsBitmap.EndInit();
  189. img.Stretch = Stretch.Fill;
  190. img.Source = interimsBitmap;
  191. return interimsBitmap;
  192. }
  193. private void StatusImage_MouseRightButtonUp(object sender, MouseButtonEventArgs e)
  194. {
  195. ContextMenu cm = new ContextMenu();
  196. var currentScreen = System.Windows.Forms.Screen.FromHandle(new System.Windows.Interop.WindowInteropHelper(this).Handle);
  197. string currentScreenName = currentScreen.DeviceName.Replace("\\", "").Replace(".", "");
  198. MenuItem identifyItem = new MenuItem();
  199. identifyItem.Header = currentScreenName;
  200. identifyItem.IsEnabled = false;
  201. MenuItem selectionItemHost = new MenuItem();
  202. selectionItemHost.Header = "Zeige/Verstecke auf...";
  203. var screenList = System.Windows.Forms.Screen.AllScreens.ToList().OrderBy(o => o.DeviceName);
  204. foreach (System.Windows.Forms.Screen screen in screenList)
  205. {
  206. MenuItem newScreenMenuItem = new MenuItem();
  207. newScreenMenuItem.IsCheckable = true;
  208. newScreenMenuItem.Header = screen.DeviceName.Replace("\\", "").Replace(".", "");
  209. newScreenMenuItem.Click += NewScreenMenuItem_Click;
  210. var isVisible = Helper.MainWindowList.FirstOrDefault(o => o.Name == screen.DeviceName.Replace("\\", "").Replace(".", "") && o.IsVisible == true);
  211. if (isVisible != null)
  212. {
  213. newScreenMenuItem.IsChecked = true;
  214. if (Helper.MainWindowList.Where(o => o.IsVisible).ToList().Count == 1)
  215. newScreenMenuItem.IsEnabled = false;
  216. }
  217. else
  218. newScreenMenuItem.IsChecked = false;
  219. selectionItemHost.Items.Add(newScreenMenuItem);
  220. }
  221. MenuItem closeItem = new MenuItem();
  222. closeItem.Header = "Internet-Checker beenden";
  223. closeItem.Name = "CloseInternetChecker";
  224. closeItem.Click += CloseItem_Click;
  225. MenuItem versionItem = new MenuItem();
  226. versionItem.Header = "v" + GetApplicationVersion().ToString();
  227. versionItem.IsEnabled = false;
  228. versionItem.FontSize = 10;
  229. versionItem.HorizontalAlignment = HorizontalAlignment.Right;
  230. cm.Items.Add(identifyItem);
  231. cm.Items.Add(new Separator());
  232. cm.Items.Add(selectionItemHost);
  233. cm.Items.Add(new Separator());
  234. cm.Items.Add(closeItem);
  235. cm.Items.Add(new Separator());
  236. cm.Items.Add(versionItem);
  237. StatusImage.ContextMenu = cm;
  238. }
  239. private void Window_Loaded(object sender, RoutedEventArgs e)
  240. {
  241. //Hide window(s) from "Alt + Tab" switcher
  242. WindowInteropHelper wndHelper = new WindowInteropHelper(this);
  243. int exStyle = (int)GetWindowLong(wndHelper.Handle, (int)GetWindowLongFields.GWL_EXSTYLE);
  244. exStyle |= (int)ExtendedWindowStyles.WS_EX_TOOLWINDOW;
  245. SetWindowLong(wndHelper.Handle, (int)GetWindowLongFields.GWL_EXSTYLE, (IntPtr)exStyle);
  246. }
  247. private void NewScreenMenuItem_Click(object sender, RoutedEventArgs e)
  248. {
  249. MenuItem currentMenuItem = (MenuItem)sender;
  250. MainWindowModel selectedMainWindow = Helper.MainWindowList.FirstOrDefault(o => o.Name == currentMenuItem.Header.ToString());
  251. System.Windows.Forms.Screen selectedScreen = System.Windows.Forms.Screen.AllScreens.FirstOrDefault(o => o.DeviceName.Contains(currentMenuItem.Header.ToString()));
  252. if (selectedMainWindow != null)
  253. {
  254. if (currentMenuItem.IsChecked)
  255. {
  256. selectedMainWindow.MainWindow.Visibility = Visibility.Visible;
  257. selectedMainWindow.IsVisible = true;
  258. }
  259. else
  260. {
  261. selectedMainWindow.MainWindow.Visibility = Visibility.Collapsed;
  262. selectedMainWindow.IsVisible = false;
  263. }
  264. }
  265. else
  266. {
  267. selectedMainWindow.MainWindow.Visibility = Visibility.Visible;
  268. selectedMainWindow.IsVisible = true;
  269. }
  270. }
  271. private void CloseItem_Click(object sender, RoutedEventArgs e)
  272. {
  273. MessageBoxResult result = MessageBox.Show("Internet-Checker beenden?", "Beenden?", MessageBoxButton.YesNo, MessageBoxImage.Information);
  274. if (result == MessageBoxResult.Yes)
  275. {
  276. foreach (MainWindowModel mainWindow in Helper.MainWindowList)
  277. {
  278. mainWindow.MainWindow.Close();
  279. }
  280. }
  281. }
  282. private void DownloadFile()
  283. {
  284. try
  285. {
  286. _updateTimer.Stop();
  287. WebClient webClient = new WebClient();
  288. webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(Completed);
  289. webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(ProgressChanged);
  290. string path = Directory.GetCurrentDirectory();
  291. webClient.DownloadFileAsync(new Uri("https://www.dropbox.com/s/vlyg4aj3aoq081n/InternetChecker.exe?dl=1"), path + "\\new.exe");
  292. }
  293. catch
  294. {
  295. _updateTimer.Start();
  296. }
  297. }
  298. private void ProgressChanged(object sender, DownloadProgressChangedEventArgs e)
  299. {
  300. //progressBar.Value = e.ProgressPercentage;
  301. }
  302. private void Completed(object sender, AsyncCompletedEventArgs e)
  303. {
  304. Helper.WaitingForUpdate = true;
  305. foreach (MainWindowModel mainWindow in Helper.MainWindowList)
  306. {
  307. mainWindow.MainWindow.Close();
  308. }
  309. }
  310. private string CreateCMDScript()
  311. {
  312. string path = "C:\\Temp";
  313. string cmdFilePath = path + "\\update_ic.bat";
  314. if (!Directory.Exists(path))
  315. Directory.CreateDirectory(path);
  316. string[] command = new string[7];
  317. command[0] = "@echo off";
  318. command[1] = "timeout /t 10 >nul";
  319. command[2] = "cd " + Directory.GetCurrentDirectory();
  320. command[3] = "DEL \"" + System.IO.Path.GetFileName(System.Reflection.Assembly.GetEntryAssembly().Location) + "\" /F/Q";
  321. command[4] = "rename \"new.exe\" \"" + System.IO.Path.GetFileName(System.Reflection.Assembly.GetEntryAssembly().Location) + "\"";
  322. command[5] = "\"" + System.IO.Path.GetFileName(System.Reflection.Assembly.GetEntryAssembly().Location) + "\"";
  323. command[6] = "exit";
  324. File.WriteAllLines(cmdFilePath, command);
  325. return cmdFilePath;
  326. }
  327. private async void ExecuteScriptFile(string cmdFile)
  328. {
  329. ProcessStartInfo info = new ProcessStartInfo(cmdFile, "/K chcp 65001");
  330. info.CreateNoWindow = true;
  331. info.WindowStyle = ProcessWindowStyle.Hidden;
  332. Process process = Process.Start(info);
  333. await Task.Delay(2500);
  334. foreach (var processWindows in Process.GetProcessesByName("InternetChecker"))
  335. {
  336. processWindows.Kill();
  337. }
  338. }
  339. private void Window_Closed(object sender, EventArgs e)
  340. {
  341. if (this == Helper.MainWindowList.Last().MainWindow)
  342. {
  343. if (Helper.WaitingForUpdate)
  344. {
  345. string cmdFile = CreateCMDScript();
  346. ExecuteScriptFile(cmdFile);
  347. }
  348. }
  349. }
  350. private Version GetApplicationVersion()
  351. {
  352. return System.Reflection.Assembly.GetExecutingAssembly().GetName().Version;
  353. }
  354. private void CheckForUpdates()
  355. {
  356. try
  357. {
  358. Debug.WriteLine("Update-Check");
  359. //https://www.dropbox.com/s/k60z1ksncqhz5ss/version.txt?dl=1
  360. WebClient webClient = new WebClient();
  361. webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(CheckUpdateFileDownloadCompleted);
  362. if (!Directory.Exists("C:\\Temp"))
  363. Directory.CreateDirectory("C:\\Temp");
  364. webClient.DownloadFileAsync(new Uri("https://www.dropbox.com/s/k60z1ksncqhz5ss/version.txt?dl=1"), "C:\\Temp\\version_ic.txt");
  365. }
  366. catch (Exception)
  367. {
  368. }
  369. }
  370. private void CheckUpdateFileDownloadCompleted(object sender, AsyncCompletedEventArgs e)
  371. {
  372. IEnumerable<string> versionFile = File.ReadLines("C:\\Temp\\version_ic.txt");
  373. string version = versionFile.FirstOrDefault();
  374. if (version != null)
  375. {
  376. Version versionNew = Version.Parse(version);
  377. if (versionNew > System.Reflection.Assembly.GetExecutingAssembly().GetName().Version)
  378. {
  379. DownloadFile();
  380. }
  381. }
  382. }
  383. private void CleanUp()
  384. {
  385. string path = "C:\\Temp";
  386. if (Directory.Exists(path))
  387. {
  388. if (File.Exists(path + "\\update_ic.bat"))
  389. File.Delete(path + "\\update_ic.bat");
  390. if (File.Exists(path + "\\version_ic.txt"))
  391. File.Delete(path + "\\version_ic.txt");
  392. }
  393. }
  394. }
  395. }