/InternetChecker/MainWindow.xaml.cs
C# | 483 lines | 405 code | 63 blank | 15 comment | 30 complexity | 42873db885fe675dec988edc7e0dab43 MD5 | raw file
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Diagnostics;
- using System.IO;
- using System.Linq;
- using System.Net;
- using System.Net.NetworkInformation;
- using System.Net.Sockets;
- using System.Runtime.InteropServices;
- using System.Text;
- using System.Threading.Tasks;
- using System.Windows;
- using System.Windows.Controls;
- using System.Windows.Data;
- using System.Windows.Documents;
- using System.Windows.Input;
- using System.Windows.Interop;
- using System.Windows.Media;
- using System.Windows.Media.Imaging;
- using System.Windows.Navigation;
- using System.Windows.Shapes;
- using System.Windows.Threading;
- namespace InternetChecker
- {
- /// <summary>
- /// Interaktionslogik für MainWindow.xaml
- /// </summary>
- public partial class MainWindow : Window
- {
- private bool _connected;
- private bool _allFunctions;
- public DispatcherTimer _monitorUpdateTimer;
- public DispatcherTimer _updateTimer;
- public MainWindow(bool all)
- {
- CleanUp();
- _allFunctions = all;
- InitializeComponent();
- Start();
- }
- #region Window styles
- [Flags]
- public enum ExtendedWindowStyles
- {
- // ...
- WS_EX_TOOLWINDOW = 0x00000080,
- // ...
- }
- public enum GetWindowLongFields
- {
- // ...
- GWL_EXSTYLE = (-20),
- // ...
- }
- [DllImport("user32.dll")]
- public static extern IntPtr GetWindowLong(IntPtr hWnd, int nIndex);
- public static IntPtr SetWindowLong(IntPtr hWnd, int nIndex, IntPtr dwNewLong)
- {
- int error = 0;
- IntPtr result = IntPtr.Zero;
- // Win32 SetWindowLong doesn't clear error on success
- SetLastError(0);
- if (IntPtr.Size == 4)
- {
- // use SetWindowLong
- Int32 tempResult = IntSetWindowLong(hWnd, nIndex, IntPtrToInt32(dwNewLong));
- error = Marshal.GetLastWin32Error();
- result = new IntPtr(tempResult);
- }
- else
- {
- // use SetWindowLongPtr
- result = IntSetWindowLongPtr(hWnd, nIndex, dwNewLong);
- error = Marshal.GetLastWin32Error();
- }
- if ((result == IntPtr.Zero) && (error != 0))
- {
- throw new System.ComponentModel.Win32Exception(error);
- }
- return result;
- }
- [DllImport("user32.dll", EntryPoint = "SetWindowLongPtr", SetLastError = true)]
- private static extern IntPtr IntSetWindowLongPtr(IntPtr hWnd, int nIndex, IntPtr dwNewLong);
- [DllImport("user32.dll", EntryPoint = "SetWindowLong", SetLastError = true)]
- private static extern Int32 IntSetWindowLong(IntPtr hWnd, int nIndex, Int32 dwNewLong);
- private static int IntPtrToInt32(IntPtr intPtr)
- {
- return unchecked((int)intPtr.ToInt64());
- }
- [DllImport("kernel32.dll", EntryPoint = "SetLastError")]
- public static extern void SetLastError(int dwErrorCode);
- #endregion
- public void _monitorUpdateTimer_Tick(object sender, EventArgs e)
- {
- Debug.WriteLine("Monitor-Check");
- if (System.Windows.Forms.Screen.AllScreens.Count() != Helper.ScreenCount)
- {
- System.Windows.Forms.Application.Restart();
- Environment.Exit(0);
- }
- }
- public async void Start()
- {
- Helper.WaitingForUpdate = false;
- _connected = false;
- if (_allFunctions)
- {
- _monitorUpdateTimer = new DispatcherTimer();
- _monitorUpdateTimer.Tick += _monitorUpdateTimer_Tick;
- _monitorUpdateTimer.Interval = new TimeSpan(0, 0, 2);
- _monitorUpdateTimer.Start();
- _updateTimer = new DispatcherTimer();
- _updateTimer.Tick += _updateTimer_Tick;
- _updateTimer.Interval = new TimeSpan(0, 5, 0);
- _updateTimer.Start();
- }
- while (true)
- {
- try
- {
- CheckConnection();
- await Task.Delay(500);
- }
- catch (Exception/* ex*/)
- {
- //MessageBox.Show(ex.Message);
- //this.Close();
- }
- finally
- {
- await Task.Delay(500);
- }
- }
- }
- private void _updateTimer_Tick(object sender, EventArgs e)
- {
- if (!Helper.WaitingForUpdate)
- {
- CheckForUpdates();
- }
- else
- _updateTimer.Stop();
- }
- public void CheckConnection()
- {
- Ping ping = new Ping();
- ping.PingCompleted += Ping_PingCompleted;
- //ping.SendAsync("www.google.com", 1000, null);
- ping.SendAsync("8.8.8.8", 1500, null);
- }
- private void Ping_PingCompleted(object sender, PingCompletedEventArgs e)
- {
- if (e.Reply != null)
- {
- if (e.Reply.Status == IPStatus.Success)
- {
- if (!_connected)
- {
- StatusImage.Source = CreateNewImageFromSource("Assets/dot_green.png");
- _connected = true;
- }
- }
- else
- {
- if (_connected)
- {
- StatusImage.Source = CreateNewImageFromSource("Assets/dot_red.png");
- _connected = false;
- }
- }
- }
- else
- {
- if (_connected)
- {
- StatusImage.Source = CreateNewImageFromSource("Assets/dot_red.png");
- _connected = false;
- }
- }
- }
- private BitmapImage CreateNewImageFromSource(string imageSource)
- {
- Image img = new Image();
- BitmapImage interimsBitmap = new BitmapImage();
- interimsBitmap.BeginInit();
- interimsBitmap.UriSource = new Uri(imageSource, UriKind.Relative);
- interimsBitmap.EndInit();
- img.Stretch = Stretch.Fill;
- img.Source = interimsBitmap;
- return interimsBitmap;
- }
- private void StatusImage_MouseRightButtonUp(object sender, MouseButtonEventArgs e)
- {
- ContextMenu cm = new ContextMenu();
- var currentScreen = System.Windows.Forms.Screen.FromHandle(new System.Windows.Interop.WindowInteropHelper(this).Handle);
- string currentScreenName = currentScreen.DeviceName.Replace("\\", "").Replace(".", "");
- MenuItem identifyItem = new MenuItem();
- identifyItem.Header = currentScreenName;
- identifyItem.IsEnabled = false;
- MenuItem selectionItemHost = new MenuItem();
- selectionItemHost.Header = "Zeige/Verstecke auf...";
- var screenList = System.Windows.Forms.Screen.AllScreens.ToList().OrderBy(o => o.DeviceName);
- foreach (System.Windows.Forms.Screen screen in screenList)
- {
- MenuItem newScreenMenuItem = new MenuItem();
- newScreenMenuItem.IsCheckable = true;
- newScreenMenuItem.Header = screen.DeviceName.Replace("\\", "").Replace(".", "");
- newScreenMenuItem.Click += NewScreenMenuItem_Click;
- var isVisible = Helper.MainWindowList.FirstOrDefault(o => o.Name == screen.DeviceName.Replace("\\", "").Replace(".", "") && o.IsVisible == true);
- if (isVisible != null)
- {
- newScreenMenuItem.IsChecked = true;
- if (Helper.MainWindowList.Where(o => o.IsVisible).ToList().Count == 1)
- newScreenMenuItem.IsEnabled = false;
- }
- else
- newScreenMenuItem.IsChecked = false;
- selectionItemHost.Items.Add(newScreenMenuItem);
- }
- MenuItem closeItem = new MenuItem();
- closeItem.Header = "Internet-Checker beenden";
- closeItem.Name = "CloseInternetChecker";
- closeItem.Click += CloseItem_Click;
- MenuItem versionItem = new MenuItem();
- versionItem.Header = "v" + GetApplicationVersion().ToString();
- versionItem.IsEnabled = false;
- versionItem.FontSize = 10;
- versionItem.HorizontalAlignment = HorizontalAlignment.Right;
- cm.Items.Add(identifyItem);
- cm.Items.Add(new Separator());
- cm.Items.Add(selectionItemHost);
- cm.Items.Add(new Separator());
- cm.Items.Add(closeItem);
- cm.Items.Add(new Separator());
- cm.Items.Add(versionItem);
- StatusImage.ContextMenu = cm;
- }
- private void Window_Loaded(object sender, RoutedEventArgs e)
- {
- //Hide window(s) from "Alt + Tab" switcher
- WindowInteropHelper wndHelper = new WindowInteropHelper(this);
- int exStyle = (int)GetWindowLong(wndHelper.Handle, (int)GetWindowLongFields.GWL_EXSTYLE);
- exStyle |= (int)ExtendedWindowStyles.WS_EX_TOOLWINDOW;
- SetWindowLong(wndHelper.Handle, (int)GetWindowLongFields.GWL_EXSTYLE, (IntPtr)exStyle);
- }
- private void NewScreenMenuItem_Click(object sender, RoutedEventArgs e)
- {
- MenuItem currentMenuItem = (MenuItem)sender;
- MainWindowModel selectedMainWindow = Helper.MainWindowList.FirstOrDefault(o => o.Name == currentMenuItem.Header.ToString());
- System.Windows.Forms.Screen selectedScreen = System.Windows.Forms.Screen.AllScreens.FirstOrDefault(o => o.DeviceName.Contains(currentMenuItem.Header.ToString()));
- if (selectedMainWindow != null)
- {
- if (currentMenuItem.IsChecked)
- {
- selectedMainWindow.MainWindow.Visibility = Visibility.Visible;
- selectedMainWindow.IsVisible = true;
- }
- else
- {
- selectedMainWindow.MainWindow.Visibility = Visibility.Collapsed;
- selectedMainWindow.IsVisible = false;
- }
- }
- else
- {
- selectedMainWindow.MainWindow.Visibility = Visibility.Visible;
- selectedMainWindow.IsVisible = true;
- }
- }
- private void CloseItem_Click(object sender, RoutedEventArgs e)
- {
- MessageBoxResult result = MessageBox.Show("Internet-Checker beenden?", "Beenden?", MessageBoxButton.YesNo, MessageBoxImage.Information);
- if (result == MessageBoxResult.Yes)
- {
- foreach (MainWindowModel mainWindow in Helper.MainWindowList)
- {
- mainWindow.MainWindow.Close();
- }
- }
- }
- private void DownloadFile()
- {
- try
- {
- _updateTimer.Stop();
- WebClient webClient = new WebClient();
- webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(Completed);
- webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(ProgressChanged);
- string path = Directory.GetCurrentDirectory();
- webClient.DownloadFileAsync(new Uri("https://www.dropbox.com/s/vlyg4aj3aoq081n/InternetChecker.exe?dl=1"), path + "\\new.exe");
- }
- catch
- {
- _updateTimer.Start();
- }
- }
- private void ProgressChanged(object sender, DownloadProgressChangedEventArgs e)
- {
- //progressBar.Value = e.ProgressPercentage;
- }
- private void Completed(object sender, AsyncCompletedEventArgs e)
- {
- Helper.WaitingForUpdate = true;
- foreach (MainWindowModel mainWindow in Helper.MainWindowList)
- {
- mainWindow.MainWindow.Close();
- }
- }
- private string CreateCMDScript()
- {
- string path = "C:\\Temp";
- string cmdFilePath = path + "\\update_ic.bat";
- if (!Directory.Exists(path))
- Directory.CreateDirectory(path);
- string[] command = new string[7];
- command[0] = "@echo off";
- command[1] = "timeout /t 10 >nul";
- command[2] = "cd " + Directory.GetCurrentDirectory();
- command[3] = "DEL \"" + System.IO.Path.GetFileName(System.Reflection.Assembly.GetEntryAssembly().Location) + "\" /F/Q";
- command[4] = "rename \"new.exe\" \"" + System.IO.Path.GetFileName(System.Reflection.Assembly.GetEntryAssembly().Location) + "\"";
- command[5] = "\"" + System.IO.Path.GetFileName(System.Reflection.Assembly.GetEntryAssembly().Location) + "\"";
- command[6] = "exit";
- File.WriteAllLines(cmdFilePath, command);
- return cmdFilePath;
- }
- private async void ExecuteScriptFile(string cmdFile)
- {
- ProcessStartInfo info = new ProcessStartInfo(cmdFile, "/K chcp 65001");
- info.CreateNoWindow = true;
- info.WindowStyle = ProcessWindowStyle.Hidden;
- Process process = Process.Start(info);
- await Task.Delay(2500);
- foreach (var processWindows in Process.GetProcessesByName("InternetChecker"))
- {
- processWindows.Kill();
- }
- }
- private void Window_Closed(object sender, EventArgs e)
- {
- if (this == Helper.MainWindowList.Last().MainWindow)
- {
- if (Helper.WaitingForUpdate)
- {
- string cmdFile = CreateCMDScript();
- ExecuteScriptFile(cmdFile);
- }
- }
- }
- private Version GetApplicationVersion()
- {
- return System.Reflection.Assembly.GetExecutingAssembly().GetName().Version;
- }
- private void CheckForUpdates()
- {
- try
- {
- Debug.WriteLine("Update-Check");
- //https://www.dropbox.com/s/k60z1ksncqhz5ss/version.txt?dl=1
- WebClient webClient = new WebClient();
- webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(CheckUpdateFileDownloadCompleted);
- if (!Directory.Exists("C:\\Temp"))
- Directory.CreateDirectory("C:\\Temp");
- webClient.DownloadFileAsync(new Uri("https://www.dropbox.com/s/k60z1ksncqhz5ss/version.txt?dl=1"), "C:\\Temp\\version_ic.txt");
- }
- catch (Exception)
- {
- }
- }
- private void CheckUpdateFileDownloadCompleted(object sender, AsyncCompletedEventArgs e)
- {
- IEnumerable<string> versionFile = File.ReadLines("C:\\Temp\\version_ic.txt");
- string version = versionFile.FirstOrDefault();
- if (version != null)
- {
- Version versionNew = Version.Parse(version);
- if (versionNew > System.Reflection.Assembly.GetExecutingAssembly().GetName().Version)
- {
- DownloadFile();
- }
- }
- }
- private void CleanUp()
- {
- string path = "C:\\Temp";
- if (Directory.Exists(path))
- {
- if (File.Exists(path + "\\update_ic.bat"))
- File.Delete(path + "\\update_ic.bat");
- if (File.Exists(path + "\\version_ic.txt"))
- File.Delete(path + "\\version_ic.txt");
- }
- }
- }
- }