public void Reload() { Services.Clear(); Services.Add(new Service() { Content = Translate.fmt("svc_all"), Value = "*", Group = Translate.fmt("lbl_selec") }); foreach (ServiceHelper.ServiceInfo svc in ServiceHelper.GetAllServices().OrderBy(x => x.DisplayName)) { Services.Add(new Service() { Value = svc.ServiceName, Content = svc.DisplayName + " (" + svc.ServiceName + ")", Group = Translate.fmt("lbl_known") }); } }
public void DoUpdate(ProgramSet progSet) { this.progSet = progSet; SuspendChange++; ImgFunc.GetIconAsync(progSet.GetIcon(), icon.Width, (ImageSource src) => { if (Application.Current != null) { Application.Current.Dispatcher.Invoke(new Action(() => { icon.Source = src; })); } return(0); }); //name.Content = process.Name; if (name.IsReadOnly) { name.Text = progSet.config.Name; } var Presets = App.presets.GetProgPins(progSet.guid); chkPin.IsChecked = Presets.Count > 0; chkPin.ToolTip = string.Join("\r\n", Presets); int blockedConnections = 0; int allowedConnections = 0; int socketCount = 0; UInt64 uploadRate = 0; UInt64 downloadRate = 0; foreach (Program prog in progSet.Programs.Values) { blockedConnections += prog.BlockedCount; allowedConnections += prog.AllowedCount; socketCount += prog.SocketCount; uploadRate += prog.UploadRate; downloadRate += prog.DownloadRate; } info.Content = Translate.fmt("lbl_prog_info", blockedConnections, allowedConnections, socketCount, FileOps.FormatSize((decimal)uploadRate), FileOps.FormatSize((decimal)downloadRate)); WpfFunc.CmbSelect(category, progSet.config.Category == null ? "" : progSet.config.Category); WpfFunc.CmbSelect(cmbAccess, progSet.config.GetAccess().ToString()); if (progSet.config.NetAccess != ProgramConfig.AccessLevels.Unconfigured && progSet.config.NetAccess != progSet.config.CurAccess) { cmbAccess.Background /*grid.Background*/ = FindResource("Stripes") as DrawingBrush; } else { cmbAccess.Background = GetAccessColor(progSet.config.GetAccess()); } chkNotify.IsChecked = progSet.config.GetNotify(); progGrid.Items.Clear(); foreach (Program prog in progSet.Programs.Values) { progGrid.Items.Insert(0, new ProgEntry(prog)); } btnSplit.IsEnabled = progSet.Programs.Count > 1; SuspendChange--; }
public bool TestTweak(Tweak tweak, bool fixChanged = false) { if (!tweak.IsAvailable()) { return(false); } bool status; if (AdminFunc.IsAdministrator() || tweak.usrLevel || !App.client.IsConnected()) { status = TweakEngine.TestTweak(tweak); } else { status = App.client.TestTweak(tweak); } if (tweak.Status != status) { tweak.Status = status; tweak.LastChangeTime = DateTime.Now; Dictionary <string, string> Params = new Dictionary <string, string>(); Params.Add("Name", tweak.Name); Params.Add("Group", tweak.Group); Params.Add("Category", tweak.Category); if (tweak.Status == false && tweak.State != Tweak.States.Unsellected) { if (fixChanged == true && tweak.FixFailed == false) { ApplyTweak(tweak); if (TestTweak(tweak, false) != true) { tweak.FixFailed = true; App.LogError(App.EventIDs.TweakError, Params, App.EventFlags.Notifications, Translate.fmt("msg_tweak_stuck", tweak.Name, tweak.Group)); } else { tweak.FixedCount++; App.LogInfo(App.EventIDs.TweakFixed, Params, App.EventFlags.Notifications, Translate.fmt("msg_tweak_fixed", tweak.Name, tweak.Group)); } } else { App.LogWarning(App.EventIDs.TweakChanged, Params, App.EventFlags.Notifications, Translate.fmt("msg_tweak_un_done", tweak.Name, tweak.Group)); } } } return(status); }
public bool Load(Dictionary <string, TweakStore.Category> Categorys) { if (!File.Exists(App.dataPath + @"\Tweaks.xml")) { return(false); } try { XmlDocument xDoc = new XmlDocument(); xDoc.Load(App.dataPath + @"\Tweaks.xml"); double fileVersion = 0.0; double.TryParse(xDoc.DocumentElement.GetAttribute("Version"), out fileVersion); if (fileVersion != xmlVersion) { if (fileVersion != 0 && fileVersion < xmlVersion) { FileOps.MoveFile(App.dataPath + @"\Tweaks.xml", App.dataPath + @"\Tweaks_old.xml", true); App.LogWarning(App.EventIDs.AppWarning, null, App.EventFlags.Notifications, Translate.fmt("msg_tweaks_updated", App.dataPath + @"\Tweaks_old.xml")); } else { App.LogError("Failed to load tweaklist, unknown file version {0}, expected {1}", fileVersion, xmlVersion); } return(false); } int TotalCount = 0; int ErrorCount = 0; foreach (XmlNode node in xDoc.DocumentElement.ChildNodes) { TotalCount++; Tweak tweak = new Tweak(); if (!tweak.Load(node)) { ErrorCount++; continue; } TweakStore.Category tweak_cat; if (!Categorys.TryGetValue(tweak.Category, out tweak_cat)) { tweak_cat = new TweakStore.Category(tweak.Category); Categorys.Add(tweak.Category, tweak_cat); } tweak_cat.Add(tweak); } if (ErrorCount != 0) { App.LogError("Failed to load {0} tweak entries out of {1}", ErrorCount, TotalCount); } App.LogInfo("TweakManager loaded {0} entries", TotalCount - ErrorCount); } catch (Exception err) { AppLog.Exception(err); return(false); } return(true); }
static bool ExecuteCommands() { if (TestArg("-help") || TestArg("/?")) { string Message = "Available command line options\r\n"; string[] Help = { "Available Console Commands:", "========================================", "", "-state\t\t\tShow instalation state", "-uninstall\t\tUninstall Private Win10", "-shutdown\t\tClose Private Win10 instances", "-restart\t\tRestart Win10 and reload settings", "", "-svc_install\t\tInstall priv10 service (invokes -log_install)", "-svc_remove\t\tRemove priv10 service", "", "-log_install\t\tInstall PrivateWin10 Custom Event Log", "-log_remove\t\tRemove PrivateWin10 Custom Event Log", "", "-restore_dns\t\tRestore original DNS Configuration", "", "-console\t\tShow console with debug output", "-help\t\t\tShow this help message" }; if (!HasConsole) { MessageBox.Show(Message + string.Join("\r\n", Help)); } else { Console.WriteLine(Message); for (int j = 0; j < Help.Length; j++) { Console.WriteLine(" " + Help[j]); } } return(true); } bool bDone = false; if (TestArg("-uninstall")) { AppLog.Debug("Uninstalling Private Win10"); bDone = true; } if (TestArg("-svc_remove") || (Priv10Service.IsInstalled() && TestArg("-uninstall"))) { AppLog.Debug("Removing Service..."); Priv10Service.Uninstall(); bDone = true; } if (TestArg("-shutdown") || TestArg("-restart") || TestArg("-restore") || TestArg("-uninstall")) { AppLog.Debug("Closing instances..."); if (Priv10Service.IsInstalled()) { Priv10Service.Terminate(); } Thread.Sleep(500); foreach (var proc in Process.GetProcessesByName(App.Key)) { if (proc.Id == ProcFunc.CurID) { continue; } proc.Kill(); } bDone = true; } if (TestArg("-restore")) { string zipPath = GetArg("-restore"); try { if (zipPath == null || !File.Exists(zipPath)) { throw new Exception("Data backup zip not specifyed or invalid path"); } Console.WriteLine("Restoring settings from {0}", zipPath); string extractPath = App.dataPath; // Normalizes the path. extractPath = Path.GetFullPath(extractPath); // Ensures that the last character on the extraction path // is the directory separator char. // Without this, a malicious zip file could try to traverse outside of the expected // extraction path. if (!extractPath.EndsWith(Path.DirectorySeparatorChar.ToString(), StringComparison.Ordinal)) { extractPath += Path.DirectorySeparatorChar; } // create data directory if (!Directory.Exists(dataPath)) { Directory.CreateDirectory(dataPath); } // ensure its writable by non administrators FileOps.SetAnyDirSec(dataPath); // Extract the backuped files using (ZipArchive archive = ZipFile.OpenRead(zipPath)) { foreach (ZipArchiveEntry entry in archive.Entries) { // Gets the full path to ensure that relative segments are removed. string destinationPath = Path.GetFullPath(Path.Combine(extractPath, entry.FullName)); // Ordinal match is safest, case-sensitive volumes can be mounted within volumes that // are case-insensitive. if (!destinationPath.StartsWith(extractPath, StringComparison.Ordinal)) { continue; } Console.WriteLine("Restored file {0}", entry.FullName); if (File.Exists(destinationPath)) { FileOps.DeleteFile(destinationPath); } else if (!Directory.Exists(Path.GetDirectoryName(destinationPath))) { Directory.CreateDirectory(Path.GetDirectoryName(destinationPath)); } entry.ExtractToFile(destinationPath); } } } catch (Exception err) { Console.WriteLine(err.Message); MessageBox.Show(Translate.fmt("msg_restore_error", err.Message), App.Title, MessageBoxButton.OK, MessageBoxImage.Stop); } bDone = true; } if (TestArg("-restart") || TestArg("-restore")) { Thread.Sleep(500); AppLog.Debug("Starting instances..."); if (Priv10Service.IsInstalled()) { Priv10Service.Startup(); } Thread.Sleep(500); ProcessStartInfo startInfo = new ProcessStartInfo(App.exePath); startInfo.UseShellExecute = true; startInfo.Verb = "runas"; Process.Start(startInfo); bDone = true; } if (TestArg("-log_remove") || (Log.UsingEventLog() && TestArg("-uninstall"))) { AppLog.Debug("Removing Event Log..."); Log.RemoveEventLog(Key); bDone = true; } if (TestArg("-svc_install")) { AppLog.Debug("Installing Service..."); Priv10Service.Install(TestArg("-svc_start")); bDone = true; } if (TestArg("-log_install") || TestArg("-svc_install")) // service needs the event log { AppLog.Debug("Setting up Event Log..."); Log.SetupEventLog(Key); bDone = true; } if (TestArg("-restore_dns") || (DnsConfigurator.IsAnyLocalDNS() && TestArg("-uninstall"))) { AppLog.Debug("Restoring DNS Config..."); DnsConfigurator.RestoreDNS(); bDone = true; } if (TestArg("-uninstall") && AdminFunc.IsSkipUac(App.Key)) { AppLog.Debug("Removing UAC Bypass..."); AdminFunc.SkipUacEnable(App.Key, false); bDone = true; } if (TestArg("-uninstall") && App.IsAutoStart()) { AppLog.Debug("Removing Autostart..."); App.AutoStart(false); bDone = true; } if (bDone) { AppLog.Debug("done"); } if (TestArg("-state")) { Console.WriteLine(); Console.WriteLine("Instalation State:"); Console.WriteLine("========================="); // 25 Console.Write("Auto Start:\t"); Console.WriteLine(App.IsAutoStart()); Console.Write("UAC Bypass:\t"); Console.WriteLine(AdminFunc.IsSkipUac(App.Key)); Console.Write("Service:\t"); Console.WriteLine(Priv10Service.IsInstalled()); Console.Write("Event Log:\t"); Console.WriteLine(Log.UsingEventLog()); Console.Write("Local DNS:\t"); Console.WriteLine(DnsConfigurator.IsAnyLocalDNS()); Console.WriteLine(); bDone = true; } if (TestArg("-wait")) { Console.WriteLine(); for (int i = 10; i >= 0; i--) { Console.Write("\r{0}% ", i); Thread.Sleep(1000); } } return(bDone); }
public static void Main(string[] args) { App.args = args; HasConsole = WinConsole.Initialize(TestArg("-console")); if (TestArg("-dbg_wait")) { MessageBox.Show("Waiting for debugger. (press ok when attached)"); } if (TestArg("-dbg_log")) { AppDomain.CurrentDomain.FirstChanceException += FirstChanceExceptionHandler; } StartModes startMode = StartModes.Normal; // Normal GUI Mode if (TestArg("-svc")) { startMode = StartModes.Service; } else if (TestArg("-engine")) { startMode = StartModes.Engine; } Log = new AppLog(Key); AppLog.ExceptionLogID = (long)EventIDs.Exception; AppLog.ExceptionCategory = (short)EventFlags.DebugEvents; if (startMode == StartModes.Normal) { Log.EnableLogging(); Log.LoadLog(); } // When running as worker we need the windows event log else if (!Log.UsingEventLog()) { Log.SetupEventLog(Key); } // load current version exePath = Process.GetCurrentProcess().MainModule.FileName; //System.Reflection.Assembly.GetExecutingAssembly().Location; FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(exePath); Version = fvi.FileMajorPart + "." + fvi.FileMinorPart; if (fvi.FileBuildPart != 0) { Version += "." + fvi.FileBuildPart; } if (fvi.FilePrivatePart != 0) { Version += (char)('a' + (fvi.FilePrivatePart - 1)); } appPath = Path.GetDirectoryName(exePath); Translate.Load(); dataPath = appPath + @"\Data"; if (File.Exists(GetINIPath())) // if an ini exists in the app path, its considdered to be a portable run { isPortable = true; AppLog.Debug("Portable Mode"); } else { string progData = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData); if (progData == null) { progData = @"C:\ProgramData"; } dataPath = progData + "\\" + Key; } AppLog.Debug("Config Directory: {0}", dataPath); // execute commandline commands if (ExecuteCommands()) { return; } if (!Directory.Exists(dataPath)) { Directory.CreateDirectory(dataPath); } if (AdminFunc.IsAdministrator()) { FileOps.SetAnyDirSec(dataPath); } App.LogInfo("PrivateWin10 Process Started, Mode {0}.", startMode.ToString()); Session = Process.GetCurrentProcess().SessionId; // setup custom assembly resolution for x86/x64 synamic compatybility AppDomain.CurrentDomain.AssemblyResolve += AssemblyResolveHandler; // is the process starting as a service/worker? if (startMode != StartModes.Normal) { engine = new Priv10Engine(); if (startMode == StartModes.Service) { using (Priv10Service svc = new Priv10Service()) ServiceBase.Run(svc); } else { engine.Run(); } return; } Thread.CurrentThread.Name = "Gui"; client = new Priv10Client(); // Encure wie have the required privilegs //if (!AdminFunc.IsDebugging()) { AppLog.Debug("Trying to connect to Engine..."); int conRes = client.Connect(1000); if (conRes == 0) { if (!AdminFunc.IsAdministrator()) { AppLog.Debug("Trying to obtain Administrative proivilegs..."); if (AdminFunc.SkipUacRun(App.Key, App.args)) { return; } AppLog.Debug("Trying to start with 'runas'..."); // Restart program and run as admin string arguments = "\"" + string.Join("\" \"", args) + "\""; ProcessStartInfo startInfo = new ProcessStartInfo(exePath, arguments); startInfo.UseShellExecute = true; startInfo.Verb = "runas"; try { Process.Start(startInfo); return; // we restarted as admin } catch { //MessageBox.Show(Translate.fmt("msg_admin_rights", mName), mName); //return; // no point in cintinuing without admin rights or an already running engine } } else if (Priv10Service.IsInstalled()) { AppLog.Debug("Trying to start service..."); if (Priv10Service.Startup()) { AppLog.Debug("Trying to connect to service..."); if (client.Connect() != 0) { AppLog.Debug("Connected to service..."); } else { AppLog.Debug("Failed to connect to service..."); } } else { AppLog.Debug("Failed to start service..."); } } } else if (conRes == -1) { MessageBox.Show(Translate.fmt("msg_dupliate_session", Title), Title); return; // no point in cintinuing without admin rights or an already running engine } } // tweaks = new TweakManager(); // if we couldn't connect to the engine start it and connect if (!client.IsConnected() && AdminFunc.IsAdministrator()) { AppLog.Debug("Starting Engine Thread..."); engine = new Priv10Engine(); engine.Start(); AppLog.Debug("... engine started."); client.Connect(); } var app = new App(); app.InitializeComponent(); InitLicense(); MainWnd = new MainWindow(); TrayIcon = new TrayIcon(); TrayIcon.Action += TrayAction; TrayIcon.Visible = (GetConfigInt("Startup", "Tray", 0) != 0) || App.TestArg("-autorun"); if (!App.TestArg("-autorun") || !TrayIcon.Visible) { MainWnd.Show(); } app.Run(); TrayIcon.DestroyNotifyicon(); client.Close(); tweaks.Store(); if (engine != null) { engine.Stop(); } }
private void category_SelectionChanged(object sender, SelectionChangedEventArgs e) { if (SuspendChange > 0) return; CategoryModel.Category cat = (category.SelectedItem as CategoryModel.Category); string Value; if (cat.SpecialCat == CategoryModel.Category.Special.AddNew) { InputWnd wnd = new InputWnd(Translate.fmt("msg_cat_name"), Translate.fmt("msg_cat_some"), App.mName); if (wnd.ShowDialog() != true || wnd.Value.Length == 0) return; Value = wnd.Value; Value = Value.Replace(',', '.'); // this is our separator so it cant be in the name bool found = false; foreach (CategoryModel.Category curCat in CatModel.Categorys) { if (Value.Equals((curCat.Content as String), StringComparison.OrdinalIgnoreCase)) found = true; } if (!found) { CatModel.Categorys.Insert(0, new CategoryModel.Category() { Content = Value, Group = Translate.fmt("cat_cats") }); category.SelectedIndex = 0; } } else if (cat.SpecialCat == CategoryModel.Category.Special.SetNone) Value = ""; else Value = (cat.Content as String); Program.config.Category = Value; App.client.UpdateProgram(Program.guid, Program.config); }
public void Update() { Dictionary <TweakManager.TweakType, TweakStat> stats = new Dictionary <TweakManager.TweakType, TweakStat>(); int active = 0; int changed = 0; foreach (TweakManager.Tweak tweak in myGroup.Tweaks.Values) { if (!tweak.IsAvailable()) { continue; } bool Status = tweak.Test(); TweakStat stat = null; if (!stats.TryGetValue(tweak.Type, out stat)) { stat = new TweakStat(); stats.Add(tweak.Type, stat); } stat.total++; if (Status) { stat.enabled++; active++; } else if (tweak.State != TweakManager.Tweak.States.Unsellected) { stat.undone++; changed++; } } if (changed > 0) { toggle.IsChecked = null; } else if (active == 0) { toggle.IsChecked = false; } else { toggle.IsChecked = true; } oldValue = toggle.IsChecked; foreach (TweakManager.TweakType type in stats.Keys) { TweakStat stat = stats[type]; string aux = ""; if (stat.undone != 0) { aux = Translate.fmt("tweak_undone", stat.undone); } boxes[type].Content = string.Format("{0}: {1}/{2}{3}", TweakManager.Tweak.GetTypeStr(type), stat.enabled, stat.total, aux); //if (stat.enabled == 0) // boxes[type].IsChecked = false; //else if (stat.enabled == stat.total) // boxes[type].IsChecked = true; //else // boxes[type].IsChecked = null; } }
public static void Main(string[] args) { App.args = args; mConsole = WinConsole.Initialize(TestArg("-console") || TestArg("-console-debug")); if (TestArg("-help") || TestArg("/?")) { ShowHelp(); return; } else if (TestArg("-dbg_wait")) { MessageBox.Show("Waiting for debugger. (press ok when attached)"); } Thread.CurrentThread.Name = "Main"; Console.WriteLine("Starting..."); AppLog Log = new AppLog(); exePath = System.Reflection.Assembly.GetExecutingAssembly().Location; FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(exePath); mVersion = fvi.FileMajorPart + "." + fvi.FileMinorPart; if (fvi.FileBuildPart != 0) { mVersion += (char)('a' + (fvi.FileBuildPart - 1)); } appPath = Path.GetDirectoryName(exePath); mSession = Process.GetCurrentProcess().SessionId; Translate.Load(); svc = new Service(mSvcName); if (TestArg("-engine")) { engine = new Engine(); engine.Run(); return; } else if (TestArg("-svc")) { if (TestArg("-install")) { Console.WriteLine("Installing service..."); svc.Install(TestArg("-start")); Console.WriteLine("... done"); } else if (TestArg("-remove")) { Console.WriteLine("Removing service..."); svc.Uninstall(); Console.WriteLine("... done"); } else { engine = new Engine(); ServiceBase.Run(svc); } return; } tweaks = new Tweaks(); client = new PipeClient(); if (!AdminFunc.IsDebugging()) { Console.WriteLine("Trying to connect to Engine..."); if (!client.Connect(1000)) { if (!AdminFunc.IsAdministrator()) { Console.WriteLine("Trying to obtain Administrative proivilegs..."); if (AdminFunc.SkipUacRun(mName, App.args)) { return; } Console.WriteLine("Trying to start with 'runas'..."); // Restart program and run as admin var exeName = Process.GetCurrentProcess().MainModule.FileName; string arguments = "\"" + string.Join("\" \"", args) + "\""; ProcessStartInfo startInfo = new ProcessStartInfo(exeName, arguments); startInfo.UseShellExecute = true; startInfo.Verb = "runas"; try { Process.Start(startInfo); return; // we restarted as admin } catch { MessageBox.Show(Translate.fmt("msg_admin_rights", mName), mName); return; // no point in cintinuing without admin rights or an already running engine } } else if (svc.IsInstalled()) { Console.WriteLine("Trying to start service..."); if (svc.Startup()) { Console.WriteLine("Trying to connect to service..."); if (client.Connect()) { Console.WriteLine("Connected to service..."); } else { Console.WriteLine("Failed to connect to service..."); } } else { Console.WriteLine("Failed to start service..."); } } } } // if we couldn't connect to the engine start it and connect if (!client.IsConnected() && AdminFunc.IsAdministrator()) { Console.WriteLine("Starting Engine Thread..."); engine = new Engine(); engine.Start(); Console.WriteLine("... engine started."); client.Connect(); } // ToDo: use a more direct communication when running in one process itf = client; cb = client; /*if (TestArg("-console-debug")) * { * Console.WriteLine("Private WinTen reporting for duty, sir!"); * Console.WriteLine(""); * * for (bool running = true; running;) * { * String Line = Console.ReadLine(); * if (Line.Length == 0) * continue; * * String Command = TextHelpers.GetLeft(ref Line).ToLower(); * * if (Command == "quit" || Command == "exit") * running = false; * * if (Command == "test") * { * } * else * { * Console.WriteLine("Unknown Command, sir!"); * continue; * } * Console.WriteLine("Yes, sir!"); * } * * return; * }*/ Console.WriteLine("Preparing GUI..."); var app = new App(); app.InitializeComponent(); InitLicense(); mTray = new TrayIcon(); mTray.Action += TrayAction; mTray.Visible = GetConfigInt("Startup", "Tray", 0) != 0; mMainWnd = new MainWindow(); if (!App.TestArg("-autorun") || !mTray.Visible) { mMainWnd.Show(); } app.Run(); mTray.DestroyNotifyicon(); client.Close(); if (engine != null) { engine.Stop(); } }
public void DoUpdate() { SuspendChange++; ImgFunc.GetIconAsync(Program.GetIcon(), icon.Width, (ImageSource src) => { if (Application.Current != null) { Application.Current.Dispatcher.Invoke(new Action(() => { icon.Source = src; })); } return 0; }); //name.Content = process.Name; name.Text = Program.config.Name; int blockedConnections = 0; int allowedConnections = 0; int socketCount = 0; UInt64 uploadRate = 0; UInt64 downloadRate = 0; foreach (Program prog in Program.Programs.Values) { blockedConnections += prog.countBlocked; allowedConnections += prog.countAllowed; socketCount += prog.SocketCount; uploadRate += prog.UploadRate; downloadRate += prog.DownloadRate; } info.Content = Translate.fmt("lbl_prog_info", blockedConnections, allowedConnections, socketCount, FileOps.FormatSize((decimal)uploadRate), FileOps.FormatSize((decimal)downloadRate)); WpfFunc.CmbSelect(category, Program.config.Category == null ? "" : Program.config.Category); if (Program.config.NetAccess == ProgramSet.Config.AccessLevels.Unconfigured) { cmbAccess.Background = GetAccessColor(Program.config.CurAccess); WpfFunc.CmbSelect(cmbAccess, Program.config.CurAccess.ToString()); } else { if (Program.config.NetAccess != ProgramSet.Config.AccessLevels.Unconfigured && Program.config.NetAccess != Program.config.CurAccess) cmbAccess.Background /*grid.Background*/ = FindResource("Stripes") as DrawingBrush; else cmbAccess.Background = GetAccessColor(Program.config.NetAccess); WpfFunc.CmbSelect(cmbAccess, Program.config.NetAccess.ToString()); } chkNotify.IsChecked = Program.config.GetNotify(); progGrid.Items.Clear(); foreach (Program prog in Program.Programs.Values) progGrid.Items.Insert(0, new ProgEntry(prog)); btnSplit.IsEnabled = Program.Programs.Count > 1; SuspendChange--; }
public TrayIcon() { this.components = new Container(); this.contextMenu = new ContextMenu(); this.menuBlock = new MenuItem() { Text = Translate.fmt("mnu_block") }; this.menuBlock.Click += new System.EventHandler(menuBlock_Click); this.menuWhitelist = new MenuItem() { Text = Translate.fmt("mnu_whitelist") }; this.menuWhitelist.Click += new System.EventHandler(menuMode_Click); this.menuBlacklist = new MenuItem() { Text = Translate.fmt("mnu_blacklist") }; this.menuBlacklist.Click += new System.EventHandler(menuMode_Click); this.menuFwDisabled = new MenuItem() { Text = Translate.fmt("mnu_open_fw") }; this.menuFwDisabled.Click += new System.EventHandler(menuMode_Click); this.menuPresets = new MenuItem() { Text = Translate.fmt("mnu_presets") }; App.client.SettingsChangedNotification += Client_SettingsChangedNotification; App.presets.PresetChange += OnPresetChanged; // Initialize menuItem1 this.menuExit = new MenuItem() { Text = Translate.fmt("mnu_exit") }; this.menuExit.Click += new System.EventHandler(this.menuExit_Click); // Initialize contextMenu1 this.contextMenu.MenuItems.AddRange(new MenuItem[] { this.menuBlock, new MenuItem("-"), this.menuWhitelist, this.menuBlacklist, this.menuFwDisabled, new MenuItem("-"), this.menuPresets, new MenuItem("-"), this.menuExit }); // Create the NotifyIcon. this.notifyIcon = new NotifyIcon(this.components); // The Icon property sets the icon that will appear // in the systray for this application. notifyIcon.Icon = System.Drawing.Icon.ExtractAssociatedIcon(App.exePath); // The ContextMenu property sets the menu that will // appear when the systray icon is right clicked. notifyIcon.ContextMenu = this.contextMenu; // The Text property sets the text that will be displayed, // in a tooltip, when the mouse hovers over the systray icon. notifyIcon.Text = FileVersionInfo.GetVersionInfo(App.exePath).FileDescription; // Handle the DoubleClick event to activate the form. notifyIcon.DoubleClick += new System.EventHandler(this.notifyIcon_DoubleClick); notifyIcon.Click += new System.EventHandler(this.notifyIcon_Click); string prefix = "pack://application:,,,/PrivateWin10;component/Resources/"; using (System.IO.Stream iconStream = Application.GetResourceStream(new Uri(prefix + "icons8-major.png")).Stream) mIcon = new Bitmap(iconStream); using (System.IO.Stream iconStream = Application.GetResourceStream(new Uri(prefix + "icon_red_ex.png")).Stream) mIcon_ex = new Bitmap(iconStream); using (System.IO.Stream iconStream = Application.GetResourceStream(new Uri(prefix + "icon_red_dot.png")).Stream) mIcon_red = new Bitmap(iconStream); using (System.IO.Stream iconStream = Application.GetResourceStream(new Uri(prefix + "icon_yellow_dot.png")).Stream) mIcon_yellow = new Bitmap(iconStream); using (System.IO.Stream iconStream = Application.GetResourceStream(new Uri(prefix + "icon_green_dot.png")).Stream) mIcon_green = new Bitmap(iconStream); using (System.IO.Stream iconStream = Application.GetResourceStream(new Uri(prefix + "icon_red_x.png")).Stream) mIcon_x = new Bitmap(iconStream); UpdateFwMode(); UpdatePresets(); mTimer.Tick += new EventHandler(OnTimerTick); mTimer.Interval = new TimeSpan(0, 0, 0, 0, 500); mTimer.Start(); }
public TrayIcon() { this.components = new Container(); this.contextMenu = new ContextMenu(); // Initialize menuItem1 this.menuBlock = new MenuItem() { Text = Translate.fmt("mnu_block") }; ProgramID id = ProgramID.NewID(ProgramID.Types.Global); ProgramSet prog = App.client.GetProgram(id, true); if (prog == null) { this.menuBlock.Enabled = false; } else { this.menuBlock.Checked = (prog.config.CurAccess == ProgramSet.Config.AccessLevels.BlockAccess); } this.menuBlock.Click += new System.EventHandler(this.menuBlock_Click); this.menuPresets = new MenuItem() { Text = Translate.fmt("mnu_presets") }; UpdatePresets(); App.presets.PresetChange += OnPresetChanged; // Initialize menuItem1 this.menuExit = new MenuItem() { Text = Translate.fmt("mnu_exit") }; this.menuExit.Click += new System.EventHandler(this.menuExit_Click); // Initialize contextMenu1 this.contextMenu.MenuItems.AddRange(new MenuItem[] { this.menuBlock, this.menuPresets, new MenuItem("-"), this.menuExit }); // Create the NotifyIcon. this.notifyIcon = new NotifyIcon(this.components); // The Icon property sets the icon that will appear // in the systray for this application. notifyIcon.Icon = System.Drawing.Icon.ExtractAssociatedIcon(App.exePath); // The ContextMenu property sets the menu that will // appear when the systray icon is right clicked. notifyIcon.ContextMenu = this.contextMenu; // The Text property sets the text that will be displayed, // in a tooltip, when the mouse hovers over the systray icon. notifyIcon.Text = FileVersionInfo.GetVersionInfo(App.exePath).FileDescription; // Handle the DoubleClick event to activate the form. notifyIcon.DoubleClick += new System.EventHandler(this.notifyIcon1_DoubleClick); notifyIcon.Click += new System.EventHandler(this.notifyIcon1_Click); mTimer.Tick += new EventHandler(OnTimerTick); mTimer.Interval = new TimeSpan(0, 0, 0, 0, 500); mTimer.Start(); }
public CategoryModel() { Categorys = new ObservableCollection <Category>(); HashSet <string> knownCats = new HashSet <string>(); foreach (ProgramSet entry in App.client.GetPrograms()) { if (entry.config.Category != null && entry.config.Category.Length > 0) { knownCats.Add(entry.config.Category); } } foreach (string cat in knownCats) { Categorys.Add(new Category() { Content = cat, Tag = cat, Group = Translate.fmt("cat_cats") }); } Categorys.Add(new Category() { SpecialCat = Category.Special.SetNone, Content = Translate.fmt("cat_none"), Tag = "", Group = Translate.fmt("cat_other") }); Categorys.Add(new Category() { SpecialCat = Category.Special.AddNew, Content = Translate.fmt("cat_new"), Tag = true, Group = Translate.fmt("cat_other") }); }
public MainWindow() { InitializeComponent(); this.Title = string.Format("{0} v{1} by David Xanatos", App.Title, App.Version); if (App.lic.LicenseStatus != QLicense.LicenseStatus.VALID) { if (!App.lic.CommercialUse) { this.Title += " - Freeware for Private NOT Commercial Use"; } else if (App.IsEvaluationExpired()) { this.Title += " - Evaluation license EXPIRED"; } else { this.Title += " - Evaluation license for Commercial Use"; } } /*else * { * if (App.lic.CommercialUse) * this.Title += " - Business Edition"; * }*/ App.LoadWnd(this, "Main"); bool HasEngine = App.client.IsConnected(); notificationWnd = new NotificationWnd(HasEngine); notificationWnd.Closed += NotificationClosed; mPages.Add("Overview", new PageItem(new OverviewPage())); mPages.Add("Privacy", new PageItem(new PrivacyPage())); mPages.Add("Firewall", new PageItem(HasEngine ? new FirewallPage() : null)); mPages.Add("Dns", new PageItem(new DnsPage())); mPages.Add("Control", new PageItem(new ControlPage())); //mPages.Add("Terminator", new PageItem(null)); //mPages.Add("VPN", new PageItem(new VPNPage())); mPages.Add("Settings", new PageItem(new SettingsPage())); mPages.Add("About", new PageItem(new AboutPage())); foreach (var page in mPages.Values) { if (page.ctrl != null) { page.ctrl.Visibility = Visibility.Collapsed; this.Main.Children.Add(page.ctrl); } } Brush brushOn = (TryFindResource("SidePanel.on") as Brush); Brush brushOff = (TryFindResource("SidePanel.off") as Brush); foreach (var val in mPages) { string name = val.Key; TabItem item = new TabItem(); val.Value.tab = item; this.SidePanel.Items.Add(item); item.KeyDown += SidePanel_Click; item.MouseLeftButtonUp += SidePanel_Click; item.Name = "PanelItem_" + name; item.Style = (TryFindResource("SidePanelItem") as Style); StackPanel panel = new StackPanel(); item.Header = panel; panel.ToolTip = Translate.fmt("lbl_" + name.ToLower()); Image image = new Image(); image.Width = 32; image.Height = 32; image.SnapsToDevicePixels = true; image.Name = "PanelItem_" + name + "_Image"; panel.Children.Add(image); Path pin = new Path(); pin.Width = 4; pin.Height = 24; pin.Margin = new Thickness(-43, -32, 0, 0); pin.Fill = TryFindResource("SidePanel.Pin") as SolidColorBrush; pin.IsHitTestVisible = false; pin.Name = "PanelItem_" + name + "_Pin"; pin.Data = new RectangleGeometry(new Rect(new Point(0, 0), new Point(4, 24))); panel.Children.Add(pin); Geometry geometry = (TryFindResource("Icon_" + name) as Geometry); image.Tag = new Tuple <DrawingImage, DrawingImage>(new DrawingImage(new GeometryDrawing(brushOn, null, geometry)), new DrawingImage(new GeometryDrawing(brushOff, null, geometry))); } //Main.Loaded += (sender, e) =>{ SwitchPage(App.GetConfig("GUI", "CurPage", "Overview")); //}; FullyLoaded = true; UpdateEnabled(); }
public void Reload() { Services.Clear(); Services.Add(new Service() { Content = Translate.fmt("svc_all"), Value = "*", Group = Translate.fmt("lbl_selec") }); foreach (ServiceController svc in ServiceController.GetServices()) { var ImagePath = ServiceHelper.GetServiceImagePath(svc.ServiceName); var ServicePath = ImagePath != null?ProcFunc.GetPathFromCmdLine(ImagePath) : ""; Services.Add(new Service() { Value = svc.ServiceName, Path = ServicePath, Content = svc.DisplayName + " (" + svc.ServiceName + ")", Group = Translate.fmt("lbl_known") }); } }
private void UpdateSysMenu() { /// Get the Handle for the Forms System Menu IntPtr systemMenuHandle = GetSystemMenu(this.Handle, false); /// Create our new System Menu items just before the Close menu item InsertMenu(systemMenuHandle, 5, MF_BYPOSITION | MF_SEPARATOR, 0, string.Empty); // <-- Add a menu seperator InsertMenu(systemMenuHandle, 6, MF_BYPOSITION | (AdminFunc.IsAdministrator() ? MF_DISABLED : MF_ENABLED), SysMenu_Setup, Translate.fmt("menu_setup")); InsertMenu(systemMenuHandle, 7, MF_BYPOSITION | (AdminFunc.IsAdministrator() ? MF_DISABLED : MF_ENABLED), SysMenu_Uninstall, Translate.fmt("menu_uninstall")); // Attach our WndProc handler to this Window HwndSource source = HwndSource.FromHwnd(this.Handle); source.AddHook(new HwndSourceHook(WndProc)); }
public static void Main(string[] args) { App.args = args; HasConsole = WinConsole.Initialize(TestArg("-console")); if (TestArg("-dbg_wait")) { MessageBox.Show("Waiting for debugger. (press ok when attached)"); } if (TestArg("-dbg_log")) { AppDomain.CurrentDomain.FirstChanceException += FirstChanceExceptionHandler; } Log = new AppLog(Key); AppLog.ExceptionLogID = (long)Priv10Logger.EventIDs.Exception; AppLog.ExceptionCategory = (short)Priv10Logger.EventFlags.DebugEvents; Log.EnableLogging(); Log.LoadLog(); // load current version exePath = Process.GetCurrentProcess().MainModule.FileName; //System.Reflection.Assembly.GetExecutingAssembly().Location; FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(exePath); Version = fvi.FileMajorPart + "." + fvi.FileMinorPart; if (fvi.FileBuildPart != 0) { Version += "." + fvi.FileBuildPart; } if (fvi.FilePrivatePart != 0) { Version += (char)('a' + (fvi.FilePrivatePart - 1)); } appPath = Path.GetDirectoryName(exePath); Translate.Load(); dataPath = appPath + @"\Data"; if (File.Exists(GetINIPath())) // if an ini exists in the app path, its considdered to be a portable run { isPortable = true; AppLog.Debug("Portable Mode"); } else { string progData = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData); if (progData == null) { progData = @"C:\ProgramData"; } dataPath = progData + "\\" + Key; } AppLog.Debug("Config Directory: {0}", dataPath); // execute commandline commands if (ExecuteCommands()) { return; } if (!Directory.Exists(dataPath)) { Directory.CreateDirectory(dataPath); } if (AdminFunc.IsAdministrator()) { FileOps.SetAnyDirSec(dataPath); } // setup custom assembly resolution for x86/x64 synamic compatybility //AppDomain.CurrentDomain.AssemblyResolve += AssemblyResolveHandler; Thread.CurrentThread.Name = "Gui"; client = new Priv10Client(); if (!AdminFunc.IsAdministrator()) { if (AdminFunc.SkipUacRun(App.Key, App.args)) { return; } if (App.GetConfigInt("Startup", "ShowSetup", 1) == 1) { AppLog.Debug("Trying to restart as admin..."); if (Restart(true)) { return; } } } AppLog.Debug("Trying to connect to Engine..."); int conRes = client.Connect(1000); if (conRes == 0) { if (Priv10Service.IsInstalled()) { if (!AdminFunc.IsAdministrator()) { MessageBox.Show(Translate.fmt("msg_admin_rights_svc", Title, SvcName), Title); Restart(true); return; } AppLog.Debug("Trying to start service..."); if (!Priv10Service.Startup()) { AppLog.Debug("Failed to start service..."); } } else if (App.GetConfigInt("Firewall", "Enabled", 0) != 0) { AppLog.Debug("Trying to start engine process..."); StartEngine(); } AppLog.Debug("Trying to connect to service..."); if (client.Connect() != 0) { AppLog.Debug("Connected to service..."); } else { AppLog.Debug("Failed to connect to service..."); } } tweaks = new TweakManager(); presets = new PresetManager(); var app = new App(); app.InitializeComponent(); InitLicense(); MainWnd = new MainWindow(); TrayIcon = new TrayIcon(); TrayIcon.Visible = (GetConfigInt("Startup", "Tray", 0) != 0) || App.TestArg("-autorun"); if (!App.TestArg("-autorun") || !TrayIcon.Visible) { MainWnd.Show(); } app.Run(); TrayIcon.DestroyNotifyicon(); presets.Store(); tweaks.Store(); if (EngineProc != null) { StopEngine(); } else { client.Close(); } }