From 047ba9806770c8dcb4975a925581e1dda64d4a43 Mon Sep 17 00:00:00 2001 From: Vincent Maas Date: Fri, 28 Apr 2023 14:35:58 +0200 Subject: [PATCH] fix auto-update, add async handlers, remove old wait for task code, final fix of combase32 crash, readd some LG actions, extend screen saver functionality --- ColorControl/AppContext.cs | 3 + ColorControl/ColorControl.csproj | 4 +- ColorControl/Common/Utils.cs | 42 +- ColorControl/Config.cs | 1 + ColorControl/Forms/ElevatedForm.cs | 2 +- ColorControl/Forms/FormUtils.cs | 46 +- ColorControl/MainForm.Designer.cs | 929 +++++++++--------- ColorControl/MainForm.cs | 229 ++--- ColorControl/Native/WinApi.cs | 18 + ColorControl/Program.cs | 51 +- ColorControl/Services/AMD/AmdPanel.cs | 25 +- ColorControl/Services/AMD/AmdService.cs | 11 +- ColorControl/Services/Common/ServiceBase.cs | 3 +- .../Services/Common/ServiceManager.cs | 68 +- .../EventDispatcher/PowerEventDispatcher.cs | 57 +- .../EventDispatcher/ProcessEventDispatcher.cs | 5 +- .../Services/GameLauncher/GamePanel.cs | 17 +- .../Services/GameLauncher/GameService.cs | 58 +- ColorControl/Services/LG/LgDevice.cs | 175 ++-- ColorControl/Services/LG/LgGameBar.cs | 13 +- ColorControl/Services/LG/LgPanel.cs | 76 +- ColorControl/Services/LG/LgService.cs | 169 ++-- ColorControl/Services/LG/RemoteControlForm.cs | 34 +- ColorControl/Services/NVIDIA/NvPanel.cs | 40 +- ColorControl/Services/NVIDIA/NvService.cs | 11 +- .../Svc/ColorControlBackgroundService.cs | 6 +- ColorControl/lgtv/LgTvConnection.cs | 29 +- ColorControl/lgtv/LgWebOsMouseService.cs | 11 +- NvAPIWrapper/NvAPIWrapper.csproj | 2 +- 29 files changed, 1129 insertions(+), 1006 deletions(-) diff --git a/ColorControl/AppContext.cs b/ColorControl/AppContext.cs index 7bfa58a..8d57f0b 100644 --- a/ColorControl/AppContext.cs +++ b/ColorControl/AppContext.cs @@ -1,4 +1,6 @@ using ColorControl.Common; +using System.ComponentModel; +using System.Threading; namespace ColorControl { @@ -10,6 +12,7 @@ namespace ColorControl public StartUpParams StartUpParams { get; private set; } public string DataPath { get; private set; } + public SynchronizationContext SynchronizationContext { get; set; } = AsyncOperationManager.SynchronizationContext; public AppContext(Config config, StartUpParams startUpParams, string dataPath) { diff --git a/ColorControl/ColorControl.csproj b/ColorControl/ColorControl.csproj index 1d87f26..f1116f0 100644 --- a/ColorControl/ColorControl.csproj +++ b/ColorControl/ColorControl.csproj @@ -18,8 +18,8 @@ Maassoft Maassoft 0 - 9.1.1.0 - 9.1.1.0 + 9.2.0.0 + 9.2.0.0 false true false diff --git a/ColorControl/Common/Utils.cs b/ColorControl/Common/Utils.cs index 761bbf2..227e93c 100644 --- a/ColorControl/Common/Utils.cs +++ b/ColorControl/Common/Utils.cs @@ -427,41 +427,6 @@ The best and suggested method to provide this is via a Windows Service. Only whe return devices; } - public static T WaitForTask(Task task) - { - if (ConsoleOpened) - { - task.Wait(); - return task.Result; - } - - while (task != null && (task.Status < TaskStatus.WaitingForChildrenToComplete)) - { - Thread.Sleep(10); - Application.DoEvents(); - } - return task.Result; - } - - public static void WaitForTask(Task task, bool doEvents = true) - { - if (ConsoleOpened) - { - task.Wait(); - return; - } - - while (task != null && (task.Status < TaskStatus.WaitingForChildrenToComplete)) - { - Thread.Sleep(10); - - if (doEvents) - { - Application.DoEvents(); - } - } - } - internal static Image GenerateGradientBitmap(int width, int height) { var bitmap = new Bitmap(512, height); @@ -1151,7 +1116,12 @@ The best and suggested method to provide this is via a Windows Service. Only whe var httpClient = new HttpClient(); using var stream = await httpClient.GetStreamAsync(url); - using var fileStream = new FileStream(filePath, FileMode.OpenOrCreate); + if (File.Exists(filePath)) + { + File.Delete(filePath); + } + + using var fileStream = new FileStream(filePath, FileMode.CreateNew); await stream.CopyToAsync(fileStream); } diff --git a/ColorControl/Config.cs b/ColorControl/Config.cs index 80cd898..d1f3642 100644 --- a/ColorControl/Config.cs +++ b/ColorControl/Config.cs @@ -24,6 +24,7 @@ namespace ColorControl public bool MinimizeToTray { get; set; } public bool CheckForUpdates { get; set; } public bool AutoInstallUpdates { get; set; } + public bool UseDarkMode { get; set; } public int DisplaySettingsDelay { get; set; } public string ScreenSaverShortcut { get; set; } public int FormWidth { get; set; } diff --git a/ColorControl/Forms/ElevatedForm.cs b/ColorControl/Forms/ElevatedForm.cs index f54cc50..23155f2 100644 --- a/ColorControl/Forms/ElevatedForm.cs +++ b/ColorControl/Forms/ElevatedForm.cs @@ -71,7 +71,7 @@ namespace ColorControl.Forms try { - Program.HandleStartupParams(startUpParams, null); + var _ = Program.HandleStartupParams(startUpParams, null); } catch (Exception) { diff --git a/ColorControl/Forms/FormUtils.cs b/ColorControl/Forms/FormUtils.cs index a841f82..5efdbc7 100644 --- a/ColorControl/Forms/FormUtils.cs +++ b/ColorControl/Forms/FormUtils.cs @@ -1,4 +1,5 @@ using ColorControl.Common; +using ColorControl.Native; using ColorControl.Services.Common; using NStandard; using NWin32; @@ -427,13 +428,56 @@ namespace ColorControl.Forms for (var i = 0; i < parent.Controls.Count; i++) { var control = parent.Controls[i]; - if (!excludedControls?.Contains(control) ?? true) + if (control is not Label && (!excludedControls?.Contains(control) ?? true)) { control.Enabled = enable; } } } + private static Dictionary _defaultColors = new Dictionary(); + + public static void SetControlTheme(Control control, Color backColor, Color foreColor) + { + var controlType = control.GetType(); + + var controlBackColor = backColor; + + if (backColor == SystemColors.Control) + { + if (_defaultColors.TryGetValue(controlType, out var newBackColor)) + { + controlBackColor = newBackColor; + } + } + else + { + if (!_defaultColors.ContainsKey(controlType)) + { + _defaultColors.Add(controlType, control.BackColor); + } + } + + //control.BackColor = controlBackColor; + //control.ForeColor = foreColor; + + //var result = WinApi.SetWindowTheme(control.Handle, "Explorer", null); + var result = WinApi.AllowDarkModeForWindow(control.Handle, true); + //var result2 = NativeMethods.SendMessageW(control.Handle, NativeConstants.WM_THEMECHANGED, 0, 0); + + for (var i = 0; i < control.Controls.Count; i++) + { + var childControl = control.Controls[i]; + + SetControlTheme(childControl, backColor, foreColor); + } + } + + public static bool IsColorLight(Windows.UI.Color color) + { + return ((5 * color.G) + (2 * color.R) + color.B) > (8 * 128); + } + public static void AddStepToTextBox(TextBox textBox, string step) { var text = textBox.Text; diff --git a/ColorControl/MainForm.Designer.cs b/ColorControl/MainForm.Designer.cs index a2d96d7..d1c78ff 100644 --- a/ColorControl/MainForm.Designer.cs +++ b/ColorControl/MainForm.Designer.cs @@ -29,599 +29,588 @@ private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MainForm)); - this.tcMain = new System.Windows.Forms.TabControl(); - this.tabOptions = new System.Windows.Forms.TabPage(); - this.grpOptionsModules = new System.Windows.Forms.GroupBox(); - this.label1 = new System.Windows.Forms.Label(); - this.chkModules = new System.Windows.Forms.CheckedListBox(); - this.grpMiscellaneousOptions = new System.Windows.Forms.GroupBox(); - this.btnSetShortcutScreenSaver = new System.Windows.Forms.Button(); - this.label11 = new System.Windows.Forms.Label(); - this.edtBlankScreenSaverShortcut = new System.Windows.Forms.TextBox(); - this.lblFixChromeFontsDescription = new System.Windows.Forms.Label(); - this.chkFixChromeFonts = new System.Windows.Forms.CheckBox(); - this.grpGeneralOptions = new System.Windows.Forms.GroupBox(); - this.chkAutoInstallUpdates = new System.Windows.Forms.CheckBox(); - this.btnStartStopService = new System.Windows.Forms.Button(); - this.btnElevationInfo = new System.Windows.Forms.Button(); - this.rbElevationService = new System.Windows.Forms.RadioButton(); - this.rbElevationProcess = new System.Windows.Forms.RadioButton(); - this.rbElevationAdmin = new System.Windows.Forms.RadioButton(); - this.label8 = new System.Windows.Forms.Label(); - this.rbElevationNone = new System.Windows.Forms.RadioButton(); - this.chkGdiScaling = new System.Windows.Forms.CheckBox(); - this.chkCheckForUpdates = new System.Windows.Forms.CheckBox(); - this.chkMinimizeToSystemTray = new System.Windows.Forms.CheckBox(); - this.chkMinimizeOnClose = new System.Windows.Forms.CheckBox(); - this.chkStartMinimized = new System.Windows.Forms.CheckBox(); - this.chkStartAfterLogin = new System.Windows.Forms.CheckBox(); - this.tabLog = new System.Windows.Forms.TabPage(); - this.lblShowLog = new System.Windows.Forms.Label(); - this.cbxLogType = new System.Windows.Forms.ComboBox(); - this.btnClearLog = new System.Windows.Forms.Button(); - this.edtLog = new System.Windows.Forms.TextBox(); - this.tabInfo = new System.Windows.Forms.TabPage(); - this.grpNVIDIAInfo = new System.Windows.Forms.GroupBox(); - this.btnRefreshNVIDIAInfo = new System.Windows.Forms.Button(); - this.tvNVIDIAInfo = new System.Windows.Forms.TreeView(); - this.groupBox3 = new System.Windows.Forms.GroupBox(); - this.lbPlugins = new System.Windows.Forms.ListBox(); - this.label7 = new System.Windows.Forms.Label(); - this.lblInfo = new System.Windows.Forms.Label(); - this.btnUpdate = new System.Windows.Forms.Button(); - this.tcMain.SuspendLayout(); - this.tabOptions.SuspendLayout(); - this.grpOptionsModules.SuspendLayout(); - this.grpMiscellaneousOptions.SuspendLayout(); - this.grpGeneralOptions.SuspendLayout(); - this.tabLog.SuspendLayout(); - this.tabInfo.SuspendLayout(); - this.grpNVIDIAInfo.SuspendLayout(); - this.groupBox3.SuspendLayout(); - this.SuspendLayout(); + tcMain = new System.Windows.Forms.TabControl(); + tabOptions = new System.Windows.Forms.TabPage(); + grpOptionsModules = new System.Windows.Forms.GroupBox(); + label1 = new System.Windows.Forms.Label(); + chkModules = new System.Windows.Forms.CheckedListBox(); + grpMiscellaneousOptions = new System.Windows.Forms.GroupBox(); + btnSetShortcutScreenSaver = new System.Windows.Forms.Button(); + label11 = new System.Windows.Forms.Label(); + edtBlankScreenSaverShortcut = new System.Windows.Forms.TextBox(); + lblFixChromeFontsDescription = new System.Windows.Forms.Label(); + chkFixChromeFonts = new System.Windows.Forms.CheckBox(); + grpGeneralOptions = new System.Windows.Forms.GroupBox(); + chkAutoInstallUpdates = new System.Windows.Forms.CheckBox(); + btnStartStopService = new System.Windows.Forms.Button(); + btnElevationInfo = new System.Windows.Forms.Button(); + rbElevationService = new System.Windows.Forms.RadioButton(); + rbElevationProcess = new System.Windows.Forms.RadioButton(); + rbElevationAdmin = new System.Windows.Forms.RadioButton(); + label8 = new System.Windows.Forms.Label(); + rbElevationNone = new System.Windows.Forms.RadioButton(); + chkGdiScaling = new System.Windows.Forms.CheckBox(); + chkCheckForUpdates = new System.Windows.Forms.CheckBox(); + chkMinimizeToSystemTray = new System.Windows.Forms.CheckBox(); + chkMinimizeOnClose = new System.Windows.Forms.CheckBox(); + chkStartMinimized = new System.Windows.Forms.CheckBox(); + chkStartAfterLogin = new System.Windows.Forms.CheckBox(); + tabLog = new System.Windows.Forms.TabPage(); + lblShowLog = new System.Windows.Forms.Label(); + cbxLogType = new System.Windows.Forms.ComboBox(); + btnClearLog = new System.Windows.Forms.Button(); + edtLog = new System.Windows.Forms.TextBox(); + tabInfo = new System.Windows.Forms.TabPage(); + grpNVIDIAInfo = new System.Windows.Forms.GroupBox(); + btnRefreshNVIDIAInfo = new System.Windows.Forms.Button(); + tvNVIDIAInfo = new System.Windows.Forms.TreeView(); + groupBox3 = new System.Windows.Forms.GroupBox(); + lbPlugins = new System.Windows.Forms.ListBox(); + label7 = new System.Windows.Forms.Label(); + lblInfo = new System.Windows.Forms.Label(); + btnUpdate = new System.Windows.Forms.Button(); + tcMain.SuspendLayout(); + tabOptions.SuspendLayout(); + grpOptionsModules.SuspendLayout(); + grpMiscellaneousOptions.SuspendLayout(); + grpGeneralOptions.SuspendLayout(); + tabLog.SuspendLayout(); + tabInfo.SuspendLayout(); + grpNVIDIAInfo.SuspendLayout(); + groupBox3.SuspendLayout(); + SuspendLayout(); // // tcMain // - this.tcMain.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) - | System.Windows.Forms.AnchorStyles.Left) - | System.Windows.Forms.AnchorStyles.Right))); - this.tcMain.Controls.Add(this.tabOptions); - this.tcMain.Controls.Add(this.tabLog); - this.tcMain.Controls.Add(this.tabInfo); - this.tcMain.Location = new System.Drawing.Point(14, 14); - this.tcMain.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); - this.tcMain.Name = "tcMain"; - this.tcMain.SelectedIndex = 0; - this.tcMain.Size = new System.Drawing.Size(1122, 567); - this.tcMain.TabIndex = 1; - this.tcMain.SelectedIndexChanged += new System.EventHandler(this.tabControl1_SelectedIndexChanged); + tcMain.Anchor = System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right; + tcMain.Controls.Add(tabOptions); + tcMain.Controls.Add(tabLog); + tcMain.Controls.Add(tabInfo); + tcMain.Location = new System.Drawing.Point(14, 14); + tcMain.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); + tcMain.Name = "tcMain"; + tcMain.SelectedIndex = 0; + tcMain.Size = new System.Drawing.Size(1122, 567); + tcMain.TabIndex = 1; + tcMain.SelectedIndexChanged += tabControl1_SelectedIndexChanged; // // tabOptions // - this.tabOptions.Controls.Add(this.grpOptionsModules); - this.tabOptions.Controls.Add(this.grpMiscellaneousOptions); - this.tabOptions.Controls.Add(this.grpGeneralOptions); - this.tabOptions.Location = new System.Drawing.Point(4, 24); - this.tabOptions.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); - this.tabOptions.Name = "tabOptions"; - this.tabOptions.Padding = new System.Windows.Forms.Padding(4, 3, 4, 3); - this.tabOptions.Size = new System.Drawing.Size(1114, 539); - this.tabOptions.TabIndex = 2; - this.tabOptions.Text = "Options"; - this.tabOptions.UseVisualStyleBackColor = true; + tabOptions.Controls.Add(grpOptionsModules); + tabOptions.Controls.Add(grpMiscellaneousOptions); + tabOptions.Controls.Add(grpGeneralOptions); + tabOptions.Location = new System.Drawing.Point(4, 24); + tabOptions.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); + tabOptions.Name = "tabOptions"; + tabOptions.Padding = new System.Windows.Forms.Padding(4, 3, 4, 3); + tabOptions.Size = new System.Drawing.Size(1114, 539); + tabOptions.TabIndex = 2; + tabOptions.Text = "Options"; + tabOptions.UseVisualStyleBackColor = true; // // grpOptionsModules // - this.grpOptionsModules.Controls.Add(this.label1); - this.grpOptionsModules.Controls.Add(this.chkModules); - this.grpOptionsModules.Location = new System.Drawing.Point(7, 187); - this.grpOptionsModules.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); - this.grpOptionsModules.Name = "grpOptionsModules"; - this.grpOptionsModules.Padding = new System.Windows.Forms.Padding(4, 3, 4, 3); - this.grpOptionsModules.Size = new System.Drawing.Size(522, 131); - this.grpOptionsModules.TabIndex = 11; - this.grpOptionsModules.TabStop = false; - this.grpOptionsModules.Text = "Modules"; + grpOptionsModules.Controls.Add(label1); + grpOptionsModules.Controls.Add(chkModules); + grpOptionsModules.Location = new System.Drawing.Point(7, 187); + grpOptionsModules.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); + grpOptionsModules.Name = "grpOptionsModules"; + grpOptionsModules.Padding = new System.Windows.Forms.Padding(4, 3, 4, 3); + grpOptionsModules.Size = new System.Drawing.Size(522, 131); + grpOptionsModules.TabIndex = 11; + grpOptionsModules.TabStop = false; + grpOptionsModules.Text = "Modules"; // // label1 // - this.label1.AutoSize = true; - this.label1.Location = new System.Drawing.Point(7, 19); - this.label1.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); - this.label1.Name = "label1"; - this.label1.Size = new System.Drawing.Size(511, 15); - this.label1.TabIndex = 7; - this.label1.Text = "Here you can disable modules you do not want. A restart is required for a change " + - "to have effect."; + label1.AutoSize = true; + label1.Location = new System.Drawing.Point(7, 19); + label1.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); + label1.Name = "label1"; + label1.Size = new System.Drawing.Size(511, 15); + label1.TabIndex = 7; + label1.Text = "Here you can disable modules you do not want. A restart is required for a change to have effect."; // // chkModules // - this.chkModules.FormattingEnabled = true; - this.chkModules.Location = new System.Drawing.Point(7, 40); - this.chkModules.Name = "chkModules"; - this.chkModules.Size = new System.Drawing.Size(507, 76); - this.chkModules.TabIndex = 0; - this.chkModules.SelectedIndexChanged += new System.EventHandler(this.chkModules_SelectedIndexChanged); + chkModules.FormattingEnabled = true; + chkModules.Location = new System.Drawing.Point(7, 40); + chkModules.Name = "chkModules"; + chkModules.Size = new System.Drawing.Size(507, 76); + chkModules.TabIndex = 0; + chkModules.SelectedIndexChanged += chkModules_SelectedIndexChanged; // // grpMiscellaneousOptions // - this.grpMiscellaneousOptions.Controls.Add(this.btnSetShortcutScreenSaver); - this.grpMiscellaneousOptions.Controls.Add(this.label11); - this.grpMiscellaneousOptions.Controls.Add(this.edtBlankScreenSaverShortcut); - this.grpMiscellaneousOptions.Controls.Add(this.lblFixChromeFontsDescription); - this.grpMiscellaneousOptions.Controls.Add(this.chkFixChromeFonts); - this.grpMiscellaneousOptions.Location = new System.Drawing.Point(7, 324); - this.grpMiscellaneousOptions.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); - this.grpMiscellaneousOptions.Name = "grpMiscellaneousOptions"; - this.grpMiscellaneousOptions.Padding = new System.Windows.Forms.Padding(4, 3, 4, 3); - this.grpMiscellaneousOptions.Size = new System.Drawing.Size(522, 131); - this.grpMiscellaneousOptions.TabIndex = 5; - this.grpMiscellaneousOptions.TabStop = false; - this.grpMiscellaneousOptions.Text = "Miscellaneous"; + grpMiscellaneousOptions.Controls.Add(btnSetShortcutScreenSaver); + grpMiscellaneousOptions.Controls.Add(label11); + grpMiscellaneousOptions.Controls.Add(edtBlankScreenSaverShortcut); + grpMiscellaneousOptions.Controls.Add(lblFixChromeFontsDescription); + grpMiscellaneousOptions.Controls.Add(chkFixChromeFonts); + grpMiscellaneousOptions.Location = new System.Drawing.Point(7, 324); + grpMiscellaneousOptions.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); + grpMiscellaneousOptions.Name = "grpMiscellaneousOptions"; + grpMiscellaneousOptions.Padding = new System.Windows.Forms.Padding(4, 3, 4, 3); + grpMiscellaneousOptions.Size = new System.Drawing.Size(522, 131); + grpMiscellaneousOptions.TabIndex = 5; + grpMiscellaneousOptions.TabStop = false; + grpMiscellaneousOptions.Text = "Miscellaneous"; // // btnSetShortcutScreenSaver // - this.btnSetShortcutScreenSaver.Location = new System.Drawing.Point(181, 98); - this.btnSetShortcutScreenSaver.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); - this.btnSetShortcutScreenSaver.Name = "btnSetShortcutScreenSaver"; - this.btnSetShortcutScreenSaver.Size = new System.Drawing.Size(40, 27); - this.btnSetShortcutScreenSaver.TabIndex = 10; - this.btnSetShortcutScreenSaver.Text = "Set"; - this.btnSetShortcutScreenSaver.UseVisualStyleBackColor = true; - this.btnSetShortcutScreenSaver.Click += new System.EventHandler(this.btnSetShortcutScreenSaver_Click); + btnSetShortcutScreenSaver.Location = new System.Drawing.Point(181, 98); + btnSetShortcutScreenSaver.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); + btnSetShortcutScreenSaver.Name = "btnSetShortcutScreenSaver"; + btnSetShortcutScreenSaver.Size = new System.Drawing.Size(40, 27); + btnSetShortcutScreenSaver.TabIndex = 10; + btnSetShortcutScreenSaver.Text = "Set"; + btnSetShortcutScreenSaver.UseVisualStyleBackColor = true; + btnSetShortcutScreenSaver.Click += btnSetShortcutScreenSaver_Click; // // label11 // - this.label11.AutoSize = true; - this.label11.Location = new System.Drawing.Point(7, 80); - this.label11.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); - this.label11.Name = "label11"; - this.label11.Size = new System.Drawing.Size(238, 15); - this.label11.TabIndex = 9; - this.label11.Text = "Set a shortcut to start the blank screensaver:"; + label11.AutoSize = true; + label11.Location = new System.Drawing.Point(7, 80); + label11.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); + label11.Name = "label11"; + label11.Size = new System.Drawing.Size(238, 15); + label11.TabIndex = 9; + label11.Text = "Set a shortcut to start the blank screensaver:"; // // edtBlankScreenSaverShortcut // - this.edtBlankScreenSaverShortcut.Location = new System.Drawing.Point(7, 101); - this.edtBlankScreenSaverShortcut.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); - this.edtBlankScreenSaverShortcut.Name = "edtBlankScreenSaverShortcut"; - this.edtBlankScreenSaverShortcut.ReadOnly = true; - this.edtBlankScreenSaverShortcut.Size = new System.Drawing.Size(165, 23); - this.edtBlankScreenSaverShortcut.TabIndex = 7; - this.edtBlankScreenSaverShortcut.KeyDown += new System.Windows.Forms.KeyEventHandler(this.edtShortcut_KeyDown); - this.edtBlankScreenSaverShortcut.KeyUp += new System.Windows.Forms.KeyEventHandler(this.edtShortcut_KeyUp); + edtBlankScreenSaverShortcut.Location = new System.Drawing.Point(7, 101); + edtBlankScreenSaverShortcut.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); + edtBlankScreenSaverShortcut.Name = "edtBlankScreenSaverShortcut"; + edtBlankScreenSaverShortcut.ReadOnly = true; + edtBlankScreenSaverShortcut.Size = new System.Drawing.Size(165, 23); + edtBlankScreenSaverShortcut.TabIndex = 7; + edtBlankScreenSaverShortcut.KeyDown += edtShortcut_KeyDown; + edtBlankScreenSaverShortcut.KeyUp += edtShortcut_KeyUp; // // lblFixChromeFontsDescription // - this.lblFixChromeFontsDescription.AutoSize = true; - this.lblFixChromeFontsDescription.Location = new System.Drawing.Point(4, 45); - this.lblFixChromeFontsDescription.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); - this.lblFixChromeFontsDescription.Name = "lblFixChromeFontsDescription"; - this.lblFixChromeFontsDescription.Size = new System.Drawing.Size(427, 15); - this.lblFixChromeFontsDescription.TabIndex = 6; - this.lblFixChromeFontsDescription.Text = "This will add the parameter --disable-lcd-text to Chrome and requires elevation."; + lblFixChromeFontsDescription.AutoSize = true; + lblFixChromeFontsDescription.Location = new System.Drawing.Point(4, 45); + lblFixChromeFontsDescription.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); + lblFixChromeFontsDescription.Name = "lblFixChromeFontsDescription"; + lblFixChromeFontsDescription.Size = new System.Drawing.Size(427, 15); + lblFixChromeFontsDescription.TabIndex = 6; + lblFixChromeFontsDescription.Text = "This will add the parameter --disable-lcd-text to Chrome and requires elevation."; // // chkFixChromeFonts // - this.chkFixChromeFonts.AutoSize = true; - this.chkFixChromeFonts.Location = new System.Drawing.Point(7, 22); - this.chkFixChromeFonts.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); - this.chkFixChromeFonts.Name = "chkFixChromeFonts"; - this.chkFixChromeFonts.Size = new System.Drawing.Size(378, 19); - this.chkFixChromeFonts.TabIndex = 4; - this.chkFixChromeFonts.Text = "ClearType: fix bad fonts in Chrome (turn on grayscale anti-aliasing)"; - this.chkFixChromeFonts.UseVisualStyleBackColor = true; - this.chkFixChromeFonts.CheckedChanged += new System.EventHandler(this.chkFixChromeFonts_CheckedChanged); + chkFixChromeFonts.AutoSize = true; + chkFixChromeFonts.Location = new System.Drawing.Point(7, 22); + chkFixChromeFonts.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); + chkFixChromeFonts.Name = "chkFixChromeFonts"; + chkFixChromeFonts.Size = new System.Drawing.Size(378, 19); + chkFixChromeFonts.TabIndex = 4; + chkFixChromeFonts.Text = "ClearType: fix bad fonts in Chrome (turn on grayscale anti-aliasing)"; + chkFixChromeFonts.UseVisualStyleBackColor = true; + chkFixChromeFonts.CheckedChanged += chkFixChromeFonts_CheckedChanged; // // grpGeneralOptions // - this.grpGeneralOptions.Controls.Add(this.chkAutoInstallUpdates); - this.grpGeneralOptions.Controls.Add(this.btnStartStopService); - this.grpGeneralOptions.Controls.Add(this.btnElevationInfo); - this.grpGeneralOptions.Controls.Add(this.rbElevationService); - this.grpGeneralOptions.Controls.Add(this.rbElevationProcess); - this.grpGeneralOptions.Controls.Add(this.rbElevationAdmin); - this.grpGeneralOptions.Controls.Add(this.label8); - this.grpGeneralOptions.Controls.Add(this.rbElevationNone); - this.grpGeneralOptions.Controls.Add(this.chkGdiScaling); - this.grpGeneralOptions.Controls.Add(this.chkCheckForUpdates); - this.grpGeneralOptions.Controls.Add(this.chkMinimizeToSystemTray); - this.grpGeneralOptions.Controls.Add(this.chkMinimizeOnClose); - this.grpGeneralOptions.Controls.Add(this.chkStartMinimized); - this.grpGeneralOptions.Controls.Add(this.chkStartAfterLogin); - this.grpGeneralOptions.Location = new System.Drawing.Point(7, 7); - this.grpGeneralOptions.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); - this.grpGeneralOptions.Name = "grpGeneralOptions"; - this.grpGeneralOptions.Padding = new System.Windows.Forms.Padding(4, 3, 4, 3); - this.grpGeneralOptions.Size = new System.Drawing.Size(522, 174); - this.grpGeneralOptions.TabIndex = 2; - this.grpGeneralOptions.TabStop = false; - this.grpGeneralOptions.Text = "General"; + grpGeneralOptions.Controls.Add(chkAutoInstallUpdates); + grpGeneralOptions.Controls.Add(btnStartStopService); + grpGeneralOptions.Controls.Add(btnElevationInfo); + grpGeneralOptions.Controls.Add(rbElevationService); + grpGeneralOptions.Controls.Add(rbElevationProcess); + grpGeneralOptions.Controls.Add(rbElevationAdmin); + grpGeneralOptions.Controls.Add(label8); + grpGeneralOptions.Controls.Add(rbElevationNone); + grpGeneralOptions.Controls.Add(chkGdiScaling); + grpGeneralOptions.Controls.Add(chkCheckForUpdates); + grpGeneralOptions.Controls.Add(chkMinimizeToSystemTray); + grpGeneralOptions.Controls.Add(chkMinimizeOnClose); + grpGeneralOptions.Controls.Add(chkStartMinimized); + grpGeneralOptions.Controls.Add(chkStartAfterLogin); + grpGeneralOptions.Location = new System.Drawing.Point(7, 7); + grpGeneralOptions.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); + grpGeneralOptions.Name = "grpGeneralOptions"; + grpGeneralOptions.Padding = new System.Windows.Forms.Padding(4, 3, 4, 3); + grpGeneralOptions.Size = new System.Drawing.Size(522, 174); + grpGeneralOptions.TabIndex = 2; + grpGeneralOptions.TabStop = false; + grpGeneralOptions.Text = "General"; // // chkAutoInstallUpdates // - this.chkAutoInstallUpdates.AutoSize = true; - this.chkAutoInstallUpdates.Location = new System.Drawing.Point(7, 147); - this.chkAutoInstallUpdates.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); - this.chkAutoInstallUpdates.Name = "chkAutoInstallUpdates"; - this.chkAutoInstallUpdates.Size = new System.Drawing.Size(179, 19); - this.chkAutoInstallUpdates.TabIndex = 66; - this.chkAutoInstallUpdates.Text = "Automatically install updates"; - this.chkAutoInstallUpdates.UseVisualStyleBackColor = true; - this.chkAutoInstallUpdates.CheckedChanged += new System.EventHandler(this.chkAutoInstallUpdates_CheckedChanged); + chkAutoInstallUpdates.AutoSize = true; + chkAutoInstallUpdates.Location = new System.Drawing.Point(7, 147); + chkAutoInstallUpdates.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); + chkAutoInstallUpdates.Name = "chkAutoInstallUpdates"; + chkAutoInstallUpdates.Size = new System.Drawing.Size(179, 19); + chkAutoInstallUpdates.TabIndex = 66; + chkAutoInstallUpdates.Text = "Automatically install updates"; + chkAutoInstallUpdates.UseVisualStyleBackColor = true; + chkAutoInstallUpdates.CheckedChanged += chkAutoInstallUpdates_CheckedChanged; // // btnStartStopService // - this.btnStartStopService.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); - this.btnStartStopService.Location = new System.Drawing.Point(474, 103); - this.btnStartStopService.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); - this.btnStartStopService.Name = "btnStartStopService"; - this.btnStartStopService.Size = new System.Drawing.Size(40, 27); - this.btnStartStopService.TabIndex = 65; - this.btnStartStopService.Text = "Start"; - this.btnStartStopService.UseVisualStyleBackColor = true; - this.btnStartStopService.Click += new System.EventHandler(this.btnStartStopService_Click); + btnStartStopService.Anchor = System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right; + btnStartStopService.Location = new System.Drawing.Point(474, 103); + btnStartStopService.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); + btnStartStopService.Name = "btnStartStopService"; + btnStartStopService.Size = new System.Drawing.Size(40, 27); + btnStartStopService.TabIndex = 65; + btnStartStopService.Text = "Start"; + btnStartStopService.UseVisualStyleBackColor = true; + btnStartStopService.Click += btnStartStopService_Click; // // btnElevationInfo // - this.btnElevationInfo.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); - this.btnElevationInfo.Location = new System.Drawing.Point(329, 41); - this.btnElevationInfo.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); - this.btnElevationInfo.Name = "btnElevationInfo"; - this.btnElevationInfo.Size = new System.Drawing.Size(22, 27); - this.btnElevationInfo.TabIndex = 64; - this.btnElevationInfo.Text = "?"; - this.btnElevationInfo.UseVisualStyleBackColor = true; - this.btnElevationInfo.Click += new System.EventHandler(this.btnElevationInfo_Click); + btnElevationInfo.Anchor = System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right; + btnElevationInfo.Location = new System.Drawing.Point(329, 41); + btnElevationInfo.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); + btnElevationInfo.Name = "btnElevationInfo"; + btnElevationInfo.Size = new System.Drawing.Size(22, 27); + btnElevationInfo.TabIndex = 64; + btnElevationInfo.Text = "?"; + btnElevationInfo.UseVisualStyleBackColor = true; + btnElevationInfo.Click += btnElevationInfo_Click; // // rbElevationService // - this.rbElevationService.AutoSize = true; - this.rbElevationService.Location = new System.Drawing.Point(216, 107); - this.rbElevationService.Name = "rbElevationService"; - this.rbElevationService.Size = new System.Drawing.Size(136, 19); - this.rbElevationService.TabIndex = 63; - this.rbElevationService.TabStop = true; - this.rbElevationService.Tag = "2"; - this.rbElevationService.Text = "Use Windows Service"; - this.rbElevationService.UseVisualStyleBackColor = true; - this.rbElevationService.CheckedChanged += new System.EventHandler(this.rbElevationNone_CheckedChanged); + rbElevationService.AutoSize = true; + rbElevationService.Location = new System.Drawing.Point(216, 107); + rbElevationService.Name = "rbElevationService"; + rbElevationService.Size = new System.Drawing.Size(136, 19); + rbElevationService.TabIndex = 63; + rbElevationService.TabStop = true; + rbElevationService.Tag = "2"; + rbElevationService.Text = "Use Windows Service"; + rbElevationService.UseVisualStyleBackColor = true; + rbElevationService.CheckedChanged += rbElevationNone_CheckedChanged; // // rbElevationProcess // - this.rbElevationProcess.AutoSize = true; - this.rbElevationProcess.Location = new System.Drawing.Point(216, 128); - this.rbElevationProcess.Name = "rbElevationProcess"; - this.rbElevationProcess.Size = new System.Drawing.Size(189, 19); - this.rbElevationProcess.TabIndex = 62; - this.rbElevationProcess.TabStop = true; - this.rbElevationProcess.Tag = "3"; - this.rbElevationProcess.Text = "Use dedicated elevated process"; - this.rbElevationProcess.UseVisualStyleBackColor = true; - this.rbElevationProcess.CheckedChanged += new System.EventHandler(this.rbElevationNone_CheckedChanged); + rbElevationProcess.AutoSize = true; + rbElevationProcess.Location = new System.Drawing.Point(216, 128); + rbElevationProcess.Name = "rbElevationProcess"; + rbElevationProcess.Size = new System.Drawing.Size(189, 19); + rbElevationProcess.TabIndex = 62; + rbElevationProcess.TabStop = true; + rbElevationProcess.Tag = "3"; + rbElevationProcess.Text = "Use dedicated elevated process"; + rbElevationProcess.UseVisualStyleBackColor = true; + rbElevationProcess.CheckedChanged += rbElevationNone_CheckedChanged; // // rbElevationAdmin // - this.rbElevationAdmin.AutoSize = true; - this.rbElevationAdmin.Location = new System.Drawing.Point(216, 86); - this.rbElevationAdmin.Name = "rbElevationAdmin"; - this.rbElevationAdmin.Size = new System.Drawing.Size(97, 19); - this.rbElevationAdmin.TabIndex = 61; - this.rbElevationAdmin.TabStop = true; - this.rbElevationAdmin.Tag = "1"; - this.rbElevationAdmin.Text = "Run as admin"; - this.rbElevationAdmin.UseVisualStyleBackColor = true; - this.rbElevationAdmin.CheckedChanged += new System.EventHandler(this.rbElevationNone_CheckedChanged); + rbElevationAdmin.AutoSize = true; + rbElevationAdmin.Location = new System.Drawing.Point(216, 86); + rbElevationAdmin.Name = "rbElevationAdmin"; + rbElevationAdmin.Size = new System.Drawing.Size(97, 19); + rbElevationAdmin.TabIndex = 61; + rbElevationAdmin.TabStop = true; + rbElevationAdmin.Tag = "1"; + rbElevationAdmin.Text = "Run as admin"; + rbElevationAdmin.UseVisualStyleBackColor = true; + rbElevationAdmin.CheckedChanged += rbElevationNone_CheckedChanged; // // label8 // - this.label8.AutoSize = true; - this.label8.Location = new System.Drawing.Point(216, 47); - this.label8.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); - this.label8.Name = "label8"; - this.label8.Size = new System.Drawing.Size(105, 15); - this.label8.TabIndex = 60; - this.label8.Text = "Elevation-method:"; + label8.AutoSize = true; + label8.Location = new System.Drawing.Point(216, 47); + label8.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); + label8.Name = "label8"; + label8.Size = new System.Drawing.Size(105, 15); + label8.TabIndex = 60; + label8.Text = "Elevation-method:"; // // rbElevationNone // - this.rbElevationNone.AutoSize = true; - this.rbElevationNone.Location = new System.Drawing.Point(216, 65); - this.rbElevationNone.Name = "rbElevationNone"; - this.rbElevationNone.Size = new System.Drawing.Size(54, 19); - this.rbElevationNone.TabIndex = 10; - this.rbElevationNone.TabStop = true; - this.rbElevationNone.Tag = "0"; - this.rbElevationNone.Text = "None"; - this.rbElevationNone.UseVisualStyleBackColor = true; - this.rbElevationNone.CheckedChanged += new System.EventHandler(this.rbElevationNone_CheckedChanged); + rbElevationNone.AutoSize = true; + rbElevationNone.Location = new System.Drawing.Point(216, 65); + rbElevationNone.Name = "rbElevationNone"; + rbElevationNone.Size = new System.Drawing.Size(54, 19); + rbElevationNone.TabIndex = 10; + rbElevationNone.TabStop = true; + rbElevationNone.Tag = "0"; + rbElevationNone.Text = "None"; + rbElevationNone.UseVisualStyleBackColor = true; + rbElevationNone.CheckedChanged += rbElevationNone_CheckedChanged; // // chkGdiScaling // - this.chkGdiScaling.AutoSize = true; - this.chkGdiScaling.Location = new System.Drawing.Point(216, 22); - this.chkGdiScaling.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); - this.chkGdiScaling.Name = "chkGdiScaling"; - this.chkGdiScaling.Size = new System.Drawing.Size(197, 19); - this.chkGdiScaling.TabIndex = 7; - this.chkGdiScaling.Text = "Use GDI Scaling (requires restart)"; - this.chkGdiScaling.UseVisualStyleBackColor = true; - this.chkGdiScaling.CheckedChanged += new System.EventHandler(this.chkGdiScaling_CheckedChanged); + chkGdiScaling.AutoSize = true; + chkGdiScaling.Location = new System.Drawing.Point(216, 22); + chkGdiScaling.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); + chkGdiScaling.Name = "chkGdiScaling"; + chkGdiScaling.Size = new System.Drawing.Size(197, 19); + chkGdiScaling.TabIndex = 7; + chkGdiScaling.Text = "Use GDI Scaling (requires restart)"; + chkGdiScaling.UseVisualStyleBackColor = true; + chkGdiScaling.CheckedChanged += chkGdiScaling_CheckedChanged; // // chkCheckForUpdates // - this.chkCheckForUpdates.AutoSize = true; - this.chkCheckForUpdates.Location = new System.Drawing.Point(7, 122); - this.chkCheckForUpdates.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); - this.chkCheckForUpdates.Name = "chkCheckForUpdates"; - this.chkCheckForUpdates.Size = new System.Drawing.Size(197, 19); - this.chkCheckForUpdates.TabIndex = 6; - this.chkCheckForUpdates.Text = "Automatically check for updates"; - this.chkCheckForUpdates.UseVisualStyleBackColor = true; - this.chkCheckForUpdates.CheckedChanged += new System.EventHandler(this.chkCheckForUpdates_CheckedChanged); + chkCheckForUpdates.AutoSize = true; + chkCheckForUpdates.Location = new System.Drawing.Point(7, 122); + chkCheckForUpdates.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); + chkCheckForUpdates.Name = "chkCheckForUpdates"; + chkCheckForUpdates.Size = new System.Drawing.Size(197, 19); + chkCheckForUpdates.TabIndex = 6; + chkCheckForUpdates.Text = "Automatically check for updates"; + chkCheckForUpdates.UseVisualStyleBackColor = true; + chkCheckForUpdates.CheckedChanged += chkCheckForUpdates_CheckedChanged; // // chkMinimizeToSystemTray // - this.chkMinimizeToSystemTray.AutoSize = true; - this.chkMinimizeToSystemTray.Location = new System.Drawing.Point(7, 97); - this.chkMinimizeToSystemTray.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); - this.chkMinimizeToSystemTray.Name = "chkMinimizeToSystemTray"; - this.chkMinimizeToSystemTray.Size = new System.Drawing.Size(152, 19); - this.chkMinimizeToSystemTray.TabIndex = 5; - this.chkMinimizeToSystemTray.Text = "Minimize to system tray"; - this.chkMinimizeToSystemTray.UseVisualStyleBackColor = true; - this.chkMinimizeToSystemTray.CheckedChanged += new System.EventHandler(this.chkMinimizeToSystemTray_CheckedChanged); + chkMinimizeToSystemTray.AutoSize = true; + chkMinimizeToSystemTray.Location = new System.Drawing.Point(7, 97); + chkMinimizeToSystemTray.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); + chkMinimizeToSystemTray.Name = "chkMinimizeToSystemTray"; + chkMinimizeToSystemTray.Size = new System.Drawing.Size(152, 19); + chkMinimizeToSystemTray.TabIndex = 5; + chkMinimizeToSystemTray.Text = "Minimize to system tray"; + chkMinimizeToSystemTray.UseVisualStyleBackColor = true; + chkMinimizeToSystemTray.CheckedChanged += chkMinimizeToSystemTray_CheckedChanged; // // chkMinimizeOnClose // - this.chkMinimizeOnClose.AutoSize = true; - this.chkMinimizeOnClose.Location = new System.Drawing.Point(7, 72); - this.chkMinimizeOnClose.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); - this.chkMinimizeOnClose.Name = "chkMinimizeOnClose"; - this.chkMinimizeOnClose.Size = new System.Drawing.Size(122, 19); - this.chkMinimizeOnClose.TabIndex = 4; - this.chkMinimizeOnClose.Text = "Minimize on close"; - this.chkMinimizeOnClose.UseVisualStyleBackColor = true; - this.chkMinimizeOnClose.CheckedChanged += new System.EventHandler(this.chkMinimizeOnClose_CheckedChanged); + chkMinimizeOnClose.AutoSize = true; + chkMinimizeOnClose.Location = new System.Drawing.Point(7, 72); + chkMinimizeOnClose.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); + chkMinimizeOnClose.Name = "chkMinimizeOnClose"; + chkMinimizeOnClose.Size = new System.Drawing.Size(122, 19); + chkMinimizeOnClose.TabIndex = 4; + chkMinimizeOnClose.Text = "Minimize on close"; + chkMinimizeOnClose.UseVisualStyleBackColor = true; + chkMinimizeOnClose.CheckedChanged += chkMinimizeOnClose_CheckedChanged; // // chkStartMinimized // - this.chkStartMinimized.AutoSize = true; - this.chkStartMinimized.Location = new System.Drawing.Point(7, 47); - this.chkStartMinimized.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); - this.chkStartMinimized.Name = "chkStartMinimized"; - this.chkStartMinimized.Size = new System.Drawing.Size(109, 19); - this.chkStartMinimized.TabIndex = 3; - this.chkStartMinimized.Text = "Start minimized"; - this.chkStartMinimized.UseVisualStyleBackColor = true; + chkStartMinimized.AutoSize = true; + chkStartMinimized.Location = new System.Drawing.Point(7, 47); + chkStartMinimized.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); + chkStartMinimized.Name = "chkStartMinimized"; + chkStartMinimized.Size = new System.Drawing.Size(109, 19); + chkStartMinimized.TabIndex = 3; + chkStartMinimized.Text = "Start minimized"; + chkStartMinimized.UseVisualStyleBackColor = true; // // chkStartAfterLogin // - this.chkStartAfterLogin.AutoSize = true; - this.chkStartAfterLogin.Location = new System.Drawing.Point(7, 22); - this.chkStartAfterLogin.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); - this.chkStartAfterLogin.Name = "chkStartAfterLogin"; - this.chkStartAfterLogin.Size = new System.Drawing.Size(183, 19); - this.chkStartAfterLogin.TabIndex = 2; - this.chkStartAfterLogin.Text = "Automatically start after login"; - this.chkStartAfterLogin.UseVisualStyleBackColor = true; - this.chkStartAfterLogin.CheckedChanged += new System.EventHandler(this.chkStartAfterLogin_CheckedChanged); + chkStartAfterLogin.AutoSize = true; + chkStartAfterLogin.Location = new System.Drawing.Point(7, 22); + chkStartAfterLogin.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); + chkStartAfterLogin.Name = "chkStartAfterLogin"; + chkStartAfterLogin.Size = new System.Drawing.Size(183, 19); + chkStartAfterLogin.TabIndex = 2; + chkStartAfterLogin.Text = "Automatically start after login"; + chkStartAfterLogin.UseVisualStyleBackColor = true; + chkStartAfterLogin.CheckedChanged += chkStartAfterLogin_CheckedChanged; // // tabLog // - this.tabLog.Controls.Add(this.lblShowLog); - this.tabLog.Controls.Add(this.cbxLogType); - this.tabLog.Controls.Add(this.btnClearLog); - this.tabLog.Controls.Add(this.edtLog); - this.tabLog.Location = new System.Drawing.Point(4, 24); - this.tabLog.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); - this.tabLog.Name = "tabLog"; - this.tabLog.Padding = new System.Windows.Forms.Padding(4, 3, 4, 3); - this.tabLog.Size = new System.Drawing.Size(1114, 539); - this.tabLog.TabIndex = 3; - this.tabLog.Text = "Log"; - this.tabLog.UseVisualStyleBackColor = true; + tabLog.Controls.Add(lblShowLog); + tabLog.Controls.Add(cbxLogType); + tabLog.Controls.Add(btnClearLog); + tabLog.Controls.Add(edtLog); + tabLog.Location = new System.Drawing.Point(4, 24); + tabLog.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); + tabLog.Name = "tabLog"; + tabLog.Padding = new System.Windows.Forms.Padding(4, 3, 4, 3); + tabLog.Size = new System.Drawing.Size(1114, 539); + tabLog.TabIndex = 3; + tabLog.Text = "Log"; + tabLog.UseVisualStyleBackColor = true; // // lblShowLog // - this.lblShowLog.AutoSize = true; - this.lblShowLog.Location = new System.Drawing.Point(8, 14); - this.lblShowLog.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); - this.lblShowLog.Name = "lblShowLog"; - this.lblShowLog.Size = new System.Drawing.Size(88, 15); - this.lblShowLog.TabIndex = 33; - this.lblShowLog.Text = "Show log from:"; + lblShowLog.AutoSize = true; + lblShowLog.Location = new System.Drawing.Point(8, 14); + lblShowLog.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); + lblShowLog.Name = "lblShowLog"; + lblShowLog.Size = new System.Drawing.Size(88, 15); + lblShowLog.TabIndex = 33; + lblShowLog.Text = "Show log from:"; // // cbxLogType // - this.cbxLogType.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; - this.cbxLogType.FormattingEnabled = true; - this.cbxLogType.Items.AddRange(new object[] { - "Main application", - "Service"}); - this.cbxLogType.Location = new System.Drawing.Point(102, 9); - this.cbxLogType.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); - this.cbxLogType.Name = "cbxLogType"; - this.cbxLogType.Size = new System.Drawing.Size(189, 23); - this.cbxLogType.TabIndex = 32; - this.cbxLogType.SelectedIndexChanged += new System.EventHandler(this.cbxLogType_SelectedIndexChanged); + cbxLogType.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; + cbxLogType.FormattingEnabled = true; + cbxLogType.Items.AddRange(new object[] { "Main application", "Service" }); + cbxLogType.Location = new System.Drawing.Point(102, 9); + cbxLogType.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); + cbxLogType.Name = "cbxLogType"; + cbxLogType.Size = new System.Drawing.Size(189, 23); + cbxLogType.TabIndex = 32; + cbxLogType.SelectedIndexChanged += cbxLogType_SelectedIndexChanged; // // btnClearLog // - this.btnClearLog.Location = new System.Drawing.Point(299, 6); - this.btnClearLog.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); - this.btnClearLog.Name = "btnClearLog"; - this.btnClearLog.Size = new System.Drawing.Size(88, 27); - this.btnClearLog.TabIndex = 2; - this.btnClearLog.Text = "Clear log"; - this.btnClearLog.UseVisualStyleBackColor = true; - this.btnClearLog.Click += new System.EventHandler(this.btnClearLog_Click); + btnClearLog.Location = new System.Drawing.Point(299, 6); + btnClearLog.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); + btnClearLog.Name = "btnClearLog"; + btnClearLog.Size = new System.Drawing.Size(88, 27); + btnClearLog.TabIndex = 2; + btnClearLog.Text = "Clear log"; + btnClearLog.UseVisualStyleBackColor = true; + btnClearLog.Click += btnClearLog_Click; // // edtLog // - this.edtLog.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) - | System.Windows.Forms.AnchorStyles.Left) - | System.Windows.Forms.AnchorStyles.Right))); - this.edtLog.Location = new System.Drawing.Point(7, 40); - this.edtLog.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); - this.edtLog.MaxLength = 327670; - this.edtLog.Multiline = true; - this.edtLog.Name = "edtLog"; - this.edtLog.ReadOnly = true; - this.edtLog.ScrollBars = System.Windows.Forms.ScrollBars.Vertical; - this.edtLog.Size = new System.Drawing.Size(1098, 478); - this.edtLog.TabIndex = 0; + edtLog.Anchor = System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right; + edtLog.Location = new System.Drawing.Point(7, 40); + edtLog.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); + edtLog.MaxLength = 327670; + edtLog.Multiline = true; + edtLog.Name = "edtLog"; + edtLog.ReadOnly = true; + edtLog.ScrollBars = System.Windows.Forms.ScrollBars.Vertical; + edtLog.Size = new System.Drawing.Size(1098, 478); + edtLog.TabIndex = 0; // // tabInfo // - this.tabInfo.Controls.Add(this.grpNVIDIAInfo); - this.tabInfo.Controls.Add(this.groupBox3); - this.tabInfo.Location = new System.Drawing.Point(4, 24); - this.tabInfo.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); - this.tabInfo.Name = "tabInfo"; - this.tabInfo.Padding = new System.Windows.Forms.Padding(4, 3, 4, 3); - this.tabInfo.Size = new System.Drawing.Size(1114, 539); - this.tabInfo.TabIndex = 4; - this.tabInfo.Text = "Info"; - this.tabInfo.UseVisualStyleBackColor = true; + tabInfo.Controls.Add(grpNVIDIAInfo); + tabInfo.Controls.Add(groupBox3); + tabInfo.Location = new System.Drawing.Point(4, 24); + tabInfo.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); + tabInfo.Name = "tabInfo"; + tabInfo.Padding = new System.Windows.Forms.Padding(4, 3, 4, 3); + tabInfo.Size = new System.Drawing.Size(1114, 539); + tabInfo.TabIndex = 4; + tabInfo.Text = "Info"; + tabInfo.UseVisualStyleBackColor = true; // // grpNVIDIAInfo // - this.grpNVIDIAInfo.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) - | System.Windows.Forms.AnchorStyles.Left) - | System.Windows.Forms.AnchorStyles.Right))); - this.grpNVIDIAInfo.Controls.Add(this.btnRefreshNVIDIAInfo); - this.grpNVIDIAInfo.Controls.Add(this.tvNVIDIAInfo); - this.grpNVIDIAInfo.Location = new System.Drawing.Point(463, 7); - this.grpNVIDIAInfo.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); - this.grpNVIDIAInfo.Name = "grpNVIDIAInfo"; - this.grpNVIDIAInfo.Padding = new System.Windows.Forms.Padding(4, 3, 4, 3); - this.grpNVIDIAInfo.Size = new System.Drawing.Size(643, 511); - this.grpNVIDIAInfo.TabIndex = 4; - this.grpNVIDIAInfo.TabStop = false; - this.grpNVIDIAInfo.Text = "NVIDIA info"; + grpNVIDIAInfo.Anchor = System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right; + grpNVIDIAInfo.Controls.Add(btnRefreshNVIDIAInfo); + grpNVIDIAInfo.Controls.Add(tvNVIDIAInfo); + grpNVIDIAInfo.Location = new System.Drawing.Point(463, 7); + grpNVIDIAInfo.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); + grpNVIDIAInfo.Name = "grpNVIDIAInfo"; + grpNVIDIAInfo.Padding = new System.Windows.Forms.Padding(4, 3, 4, 3); + grpNVIDIAInfo.Size = new System.Drawing.Size(643, 511); + grpNVIDIAInfo.TabIndex = 4; + grpNVIDIAInfo.TabStop = false; + grpNVIDIAInfo.Text = "NVIDIA info"; // // btnRefreshNVIDIAInfo // - this.btnRefreshNVIDIAInfo.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); - this.btnRefreshNVIDIAInfo.Location = new System.Drawing.Point(7, 478); - this.btnRefreshNVIDIAInfo.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); - this.btnRefreshNVIDIAInfo.Name = "btnRefreshNVIDIAInfo"; - this.btnRefreshNVIDIAInfo.Size = new System.Drawing.Size(88, 27); - this.btnRefreshNVIDIAInfo.TabIndex = 1; - this.btnRefreshNVIDIAInfo.Text = "Refresh"; - this.btnRefreshNVIDIAInfo.UseVisualStyleBackColor = true; - this.btnRefreshNVIDIAInfo.Click += new System.EventHandler(this.btnRefreshNVIDIAInfo_Click); + btnRefreshNVIDIAInfo.Anchor = System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left; + btnRefreshNVIDIAInfo.Location = new System.Drawing.Point(7, 478); + btnRefreshNVIDIAInfo.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); + btnRefreshNVIDIAInfo.Name = "btnRefreshNVIDIAInfo"; + btnRefreshNVIDIAInfo.Size = new System.Drawing.Size(88, 27); + btnRefreshNVIDIAInfo.TabIndex = 1; + btnRefreshNVIDIAInfo.Text = "Refresh"; + btnRefreshNVIDIAInfo.UseVisualStyleBackColor = true; + btnRefreshNVIDIAInfo.Click += btnRefreshNVIDIAInfo_Click; // // tvNVIDIAInfo // - this.tvNVIDIAInfo.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) - | System.Windows.Forms.AnchorStyles.Left) - | System.Windows.Forms.AnchorStyles.Right))); - this.tvNVIDIAInfo.Location = new System.Drawing.Point(7, 22); - this.tvNVIDIAInfo.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); - this.tvNVIDIAInfo.Name = "tvNVIDIAInfo"; - this.tvNVIDIAInfo.Size = new System.Drawing.Size(628, 448); - this.tvNVIDIAInfo.TabIndex = 0; + tvNVIDIAInfo.Anchor = System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right; + tvNVIDIAInfo.Location = new System.Drawing.Point(7, 22); + tvNVIDIAInfo.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); + tvNVIDIAInfo.Name = "tvNVIDIAInfo"; + tvNVIDIAInfo.Size = new System.Drawing.Size(628, 448); + tvNVIDIAInfo.TabIndex = 0; // // groupBox3 // - this.groupBox3.Controls.Add(this.lbPlugins); - this.groupBox3.Controls.Add(this.label7); - this.groupBox3.Controls.Add(this.lblInfo); - this.groupBox3.Location = new System.Drawing.Point(7, 7); - this.groupBox3.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); - this.groupBox3.Name = "groupBox3"; - this.groupBox3.Padding = new System.Windows.Forms.Padding(4, 3, 4, 3); - this.groupBox3.Size = new System.Drawing.Size(449, 254); - this.groupBox3.TabIndex = 5; - this.groupBox3.TabStop = false; - this.groupBox3.Text = "Info"; + groupBox3.Controls.Add(lbPlugins); + groupBox3.Controls.Add(label7); + groupBox3.Controls.Add(lblInfo); + groupBox3.Location = new System.Drawing.Point(7, 7); + groupBox3.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); + groupBox3.Name = "groupBox3"; + groupBox3.Padding = new System.Windows.Forms.Padding(4, 3, 4, 3); + groupBox3.Size = new System.Drawing.Size(449, 254); + groupBox3.TabIndex = 5; + groupBox3.TabStop = false; + groupBox3.Text = "Info"; // // lbPlugins // - this.lbPlugins.FormattingEnabled = true; - this.lbPlugins.HorizontalScrollbar = true; - this.lbPlugins.ItemHeight = 15; - this.lbPlugins.Location = new System.Drawing.Point(10, 77); - this.lbPlugins.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); - this.lbPlugins.Name = "lbPlugins"; - this.lbPlugins.Size = new System.Drawing.Size(432, 169); - this.lbPlugins.TabIndex = 3; + lbPlugins.FormattingEnabled = true; + lbPlugins.HorizontalScrollbar = true; + lbPlugins.ItemHeight = 15; + lbPlugins.Location = new System.Drawing.Point(10, 77); + lbPlugins.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); + lbPlugins.Name = "lbPlugins"; + lbPlugins.Size = new System.Drawing.Size(432, 169); + lbPlugins.TabIndex = 3; // // label7 // - this.label7.AutoSize = true; - this.label7.Location = new System.Drawing.Point(7, 59); - this.label7.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); - this.label7.Name = "label7"; - this.label7.Size = new System.Drawing.Size(267, 15); - this.label7.TabIndex = 2; - this.label7.Text = "This app contains the following 3rd party plugins:"; + label7.AutoSize = true; + label7.Location = new System.Drawing.Point(7, 59); + label7.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); + label7.Name = "label7"; + label7.Size = new System.Drawing.Size(267, 15); + label7.TabIndex = 2; + label7.Text = "This app contains the following 3rd party plugins:"; // // lblInfo // - this.lblInfo.AutoSize = true; - this.lblInfo.Location = new System.Drawing.Point(7, 23); - this.lblInfo.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); - this.lblInfo.Name = "lblInfo"; - this.lblInfo.Size = new System.Drawing.Size(28, 15); - this.lblInfo.TabIndex = 1; - this.lblInfo.Text = "Info"; + lblInfo.AutoSize = true; + lblInfo.Location = new System.Drawing.Point(7, 23); + lblInfo.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); + lblInfo.Name = "lblInfo"; + lblInfo.Size = new System.Drawing.Size(28, 15); + lblInfo.TabIndex = 1; + lblInfo.Text = "Info"; // // btnUpdate // - this.btnUpdate.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); - this.btnUpdate.FlatStyle = System.Windows.Forms.FlatStyle.Flat; - this.btnUpdate.ForeColor = System.Drawing.Color.Red; - this.btnUpdate.Location = new System.Drawing.Point(1055, 0); - this.btnUpdate.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); - this.btnUpdate.Name = "btnUpdate"; - this.btnUpdate.Size = new System.Drawing.Size(77, 26); - this.btnUpdate.TabIndex = 61; - this.btnUpdate.Text = "Update"; - this.btnUpdate.UseVisualStyleBackColor = true; - this.btnUpdate.Visible = false; - this.btnUpdate.Click += new System.EventHandler(this.btnUpdate_Click); + btnUpdate.Anchor = System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right; + btnUpdate.FlatStyle = System.Windows.Forms.FlatStyle.Flat; + btnUpdate.ForeColor = System.Drawing.Color.Red; + btnUpdate.Location = new System.Drawing.Point(1055, 0); + btnUpdate.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); + btnUpdate.Name = "btnUpdate"; + btnUpdate.Size = new System.Drawing.Size(77, 26); + btnUpdate.TabIndex = 61; + btnUpdate.Text = "Update"; + btnUpdate.UseVisualStyleBackColor = true; + btnUpdate.Visible = false; + btnUpdate.Click += btnUpdate_Click; // // MainForm // - this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F); - this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; - this.BackColor = System.Drawing.SystemColors.Control; - this.ClientSize = new System.Drawing.Size(1150, 594); - this.Controls.Add(this.btnUpdate); - this.Controls.Add(this.tcMain); - this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); - this.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); - this.MinimumSize = new System.Drawing.Size(1140, 611); - this.Name = "MainForm"; - this.Text = "ColorControl"; - this.Activated += new System.EventHandler(this.MainForm_Activated); - this.Deactivate += new System.EventHandler(this.MainForm_Deactivate); - this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.MainForm_FormClosing); - this.FormClosed += new System.Windows.Forms.FormClosedEventHandler(this.MainForm_FormClosed); - this.Shown += new System.EventHandler(this.MainForm_Shown); - this.ResizeBegin += new System.EventHandler(this.MainForm_ResizeBegin); - this.ResizeEnd += new System.EventHandler(this.MainForm_ResizeEnd); - this.Click += new System.EventHandler(this.MainForm_Click); - this.Resize += new System.EventHandler(this.MainForm_Resize); - this.tcMain.ResumeLayout(false); - this.tabOptions.ResumeLayout(false); - this.grpOptionsModules.ResumeLayout(false); - this.grpOptionsModules.PerformLayout(); - this.grpMiscellaneousOptions.ResumeLayout(false); - this.grpMiscellaneousOptions.PerformLayout(); - this.grpGeneralOptions.ResumeLayout(false); - this.grpGeneralOptions.PerformLayout(); - this.tabLog.ResumeLayout(false); - this.tabLog.PerformLayout(); - this.tabInfo.ResumeLayout(false); - this.grpNVIDIAInfo.ResumeLayout(false); - this.groupBox3.ResumeLayout(false); - this.groupBox3.PerformLayout(); - this.ResumeLayout(false); - + AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F); + AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + BackColor = System.Drawing.SystemColors.Control; + ClientSize = new System.Drawing.Size(1150, 594); + Controls.Add(btnUpdate); + Controls.Add(tcMain); + Icon = (System.Drawing.Icon)resources.GetObject("$this.Icon"); + Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); + MinimumSize = new System.Drawing.Size(1140, 611); + Name = "MainForm"; + Text = "ColorControl"; + Activated += MainForm_Activated; + Deactivate += MainForm_Deactivate; + FormClosing += MainForm_FormClosing; + FormClosed += MainForm_FormClosed; + Load += MainForm_Load; + Shown += MainForm_Shown; + ResizeBegin += MainForm_ResizeBegin; + ResizeEnd += MainForm_ResizeEnd; + Click += MainForm_Click; + Resize += MainForm_Resize; + tcMain.ResumeLayout(false); + tabOptions.ResumeLayout(false); + grpOptionsModules.ResumeLayout(false); + grpOptionsModules.PerformLayout(); + grpMiscellaneousOptions.ResumeLayout(false); + grpMiscellaneousOptions.PerformLayout(); + grpGeneralOptions.ResumeLayout(false); + grpGeneralOptions.PerformLayout(); + tabLog.ResumeLayout(false); + tabLog.PerformLayout(); + tabInfo.ResumeLayout(false); + grpNVIDIAInfo.ResumeLayout(false); + groupBox3.ResumeLayout(false); + groupBox3.PerformLayout(); + ResumeLayout(false); } #endregion diff --git a/ColorControl/MainForm.cs b/ColorControl/MainForm.cs index ba69db4..a73eafe 100644 --- a/ColorControl/MainForm.cs +++ b/ColorControl/MainForm.cs @@ -3,6 +3,7 @@ using ColorControl.Forms; using ColorControl.Native; using ColorControl.Services.AMD; using ColorControl.Services.Common; +using ColorControl.Services.EventDispatcher; using ColorControl.Services.GameLauncher; using ColorControl.Services.LG; using ColorControl.Services.NVIDIA; @@ -13,6 +14,7 @@ using NvAPIWrapper.Display; using NWin32; using System; using System.Collections.Generic; +using System.ComponentModel; using System.Diagnostics; using System.Drawing; using System.IO; @@ -20,6 +22,7 @@ using System.Linq; using System.Runtime.InteropServices; using System.Threading.Tasks; using System.Windows.Forms; +using Windows.UI.ViewManagement; namespace ColorControl { @@ -31,10 +34,10 @@ namespace ColorControl private static int SHORTCUTID_SCREENSAVER = -100; private static readonly Logger Logger = LogManager.GetCurrentClassLogger(); - + private readonly PowerEventDispatcher _powerEventDispatcher; + private readonly ServiceManager _serviceManager; private string _dataDir; - private NvService _nvService; private NvPanel _nvPanel; private NvDitherPanel _nvDitherPanel; @@ -43,7 +46,6 @@ namespace ColorControl private Config _config; private bool _setVisibleCalled = false; - private LgService _lgService; private LgPanel _lgPanel; private ToolStripMenuItem _nvTrayMenu; @@ -54,7 +56,6 @@ namespace ColorControl private StartUpParams StartUpParams { get; } public string _lgTabMessage { get; private set; } - private AmdService _amdService; private AmdPanel _amdPanel; private bool _skipResize; private FileVersionInfo _currentVersionInfo; @@ -62,7 +63,6 @@ namespace ColorControl private string _updateHtmlUrl; private string _downloadUrl; - private GameService _gameService; private GamePanel _gamePanel; //private KeyboardHookManager _keyboardHookManager; @@ -71,11 +71,14 @@ namespace ColorControl private Dictionary _shortcuts = new(); private Dictionary> _modules = new(); - public MainForm(AppContext appContext) + public MainForm(AppContextProvider appContextProvider, PowerEventDispatcher powerEventDispatcher, ServiceManager serviceManager) { InitializeComponent(); - StartUpParams = appContext.StartUpParams; + StartUpParams = appContextProvider.GetAppContext().StartUpParams; + appContextProvider.GetAppContext().SynchronizationContext = AsyncOperationManager.SynchronizationContext; + _powerEventDispatcher = powerEventDispatcher; + _serviceManager = serviceManager; _dataDir = Program.DataDir; _config = Program.Config; @@ -148,12 +151,13 @@ namespace ColorControl //Task.Run(() => Utils.StartPipeAsync()); + //SwitchTheme(); + AfterInitialized(); } private void MainForm_Load(object sender, EventArgs e) { - InitModules(); } private void LoadModules() @@ -241,13 +245,13 @@ namespace ColorControl //throw new Exception("bla"); Logger.Debug("Initializing NVIDIA..."); var appContextProvider = Program.ServiceProvider.GetRequiredService(); - _nvService = new NvService(appContextProvider); + _serviceManager.NvService = new NvService(appContextProvider); Logger.Debug("Initializing NVIDIA...Done."); - _nvPanel = new NvPanel(_nvService, _trayIcon, Handle); + _nvPanel = new NvPanel(_serviceManager.NvService, _trayIcon, Handle, appContextProvider); _nvPanel.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; - InitShortcut(NvPanel.SHORTCUTID_NVQA, _config.NvQuickAccessShortcut, _nvService.ToggleQuickAccessForm); + InitShortcut(NvPanel.SHORTCUTID_NVQA, _config.NvQuickAccessShortcut, _serviceManager.NvService.ToggleQuickAccessForm); return _nvPanel; } @@ -265,12 +269,12 @@ namespace ColorControl try { var appContextProvider = Program.ServiceProvider.GetRequiredService(); - _amdService = new AmdService(appContextProvider); + _serviceManager.AmdService = new AmdService(appContextProvider); - _amdPanel = new AmdPanel(_amdService, _trayIcon, Handle); + _amdPanel = new AmdPanel(_serviceManager.AmdService, _trayIcon, Handle); _amdPanel.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; - InitShortcut(AmdPanel.SHORTCUTID_AMDQA, _config.AmdQuickAccessShortcut, _amdService.ToggleQuickAccessForm); + InitShortcut(AmdPanel.SHORTCUTID_AMDQA, _config.AmdQuickAccessShortcut, _serviceManager.AmdService.ToggleQuickAccessForm); return _amdPanel; } @@ -287,13 +291,12 @@ namespace ColorControl { try { - var appContextProvider = Program.ServiceProvider.GetRequiredService(); - _gameService = new GameService(appContextProvider, HandleExternalServiceForLgDevice); + _serviceManager.GameService = Program.ServiceProvider.GetRequiredService(); - _gamePanel = new GamePanel(_gameService, _nvService, _amdService, _lgService, _trayIcon, Handle); + _gamePanel = new GamePanel(_serviceManager.GameService, _serviceManager.NvService, _serviceManager.AmdService, _serviceManager.LgService, _trayIcon, Handle); _gamePanel.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; - InitShortcut(GamePanel.SHORTCUTID_GAMEQA, _config.GameQuickAccessShortcut, _gameService.ToggleQuickAccessForm); + InitShortcut(GamePanel.SHORTCUTID_GAMEQA, _config.GameQuickAccessShortcut, _serviceManager.GameService.ToggleQuickAccessForm); return _gamePanel; } @@ -319,16 +322,15 @@ namespace ColorControl { try { - _lgService = Program.ServiceProvider.GetRequiredService(); + _serviceManager.LgService = Program.ServiceProvider.GetRequiredService(); - _lgPanel = new LgPanel(_lgService, _nvService, _amdService, _trayIcon, Handle); + _lgPanel = new LgPanel(_serviceManager.LgService, _serviceManager.NvService, _serviceManager.AmdService, _trayIcon, Handle); _lgPanel.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; _lgPanel.Init(); - LgDevice.ExternalServiceHandler = HandleExternalServiceForLgDevice; - InitShortcut(LgPanel.SHORTCUTID_GAMEBAR, _lgService.Config.GameBarShortcut, _lgPanel.ToggleGameBar); - InitShortcut(LgPanel.SHORTCUTID_LGQA, _lgService.Config.QuickAccessShortcut, _lgService.ToggleQuickAccessForm); + InitShortcut(LgPanel.SHORTCUTID_GAMEBAR, _serviceManager.LgService.Config.GameBarShortcut, _lgPanel.ToggleGameBar); + InitShortcut(LgPanel.SHORTCUTID_LGQA, _serviceManager.LgService.Config.QuickAccessShortcut, _serviceManager.LgService.ToggleQuickAccessForm); return _lgPanel; @@ -352,48 +354,12 @@ namespace ColorControl { BeginInvoke(async () => { - var preset = _lgService.GetPresets().FirstOrDefault(p => p.name == "Backlight 20"); + var preset = _serviceManager.LgService.GetPresets().FirstOrDefault(p => p.name == "Backlight 20"); - await _lgService.ApplyPreset(preset); + await _serviceManager.LgService.ApplyPreset(preset); }); } - private bool HandleExternalServiceForLgDevice(string serviceName, string[] parameters) - { - if (string.IsNullOrEmpty(serviceName) || parameters.Length == 0) - { - return false; - } - - if (_nvService != null && serviceName.Equals("NvPreset", StringComparison.OrdinalIgnoreCase)) - { - return _nvService.ApplyPreset(parameters[0]); - } - if (_nvService != null && serviceName.Equals("GsyncEnabled", StringComparison.OrdinalIgnoreCase)) - { - return _nvService.IsGsyncEnabled(); - } - if (_amdService != null && serviceName.Equals("AmdPreset", StringComparison.OrdinalIgnoreCase)) - { - return _amdService.ApplyPreset(parameters[0]); - } - if (_lgService != null && serviceName.Equals("LgPreset", StringComparison.OrdinalIgnoreCase)) - { - Utils.WaitForTask(_lgService.ApplyPreset(parameters[0])); - - return true; - } - - if (serviceName.Equals("StartProgram", StringComparison.OrdinalIgnoreCase)) - { - Utils.StartProcess(parameters[0], parameters.Length > 1 ? string.Join(" ", parameters.Skip(1)) : null, setWorkingDir: true); - - return true; - } - - return false; - } - private void InitInfo() { _currentVersionInfo = FileVersionInfo.GetVersionInfo(Path.GetFileName(Application.ExecutablePath)); @@ -461,22 +427,17 @@ namespace ColorControl GlobalSave(); - if (SystemShutdown && _lgService != null) + if (SystemShutdown) { Logger.Debug($"MainForm_FormClosing: SystemShutdown"); - var devices = _lgService.Devices.Where(d => d.PowerOffOnShutdown); - - _lgService.PowerOffDevices(devices); + _powerEventDispatcher.SendEvent(PowerEventDispatcher.Event_Shutdown); } } private void GlobalSave() { - _nvService?.GlobalSave(); - _amdService?.GlobalSave(); - _lgService?.GlobalSave(); - _gameService?.GlobalSave(); + _serviceManager.Save(); _nvPanel?.Save(); _amdPanel?.Save(); @@ -523,19 +484,19 @@ namespace ColorControl // 6. Handle what will happen once a respective hotkey is pressed else { - var preset = _nvService?.GetPresets().FirstOrDefault(x => x.id == id); + var preset = _serviceManager.NvService?.GetPresets().FirstOrDefault(x => x.id == id); if (preset != null) { _nvPanel?.ApplyNvPreset(preset); } - var amdPreset = _amdService?.GetPresets().FirstOrDefault(x => x.id == id); + var amdPreset = _serviceManager.AmdService?.GetPresets().FirstOrDefault(x => x.id == id); if (amdPreset != null) { _amdPanel?.ApplyAmdPreset(amdPreset); } - var lgPreset = _lgService?.GetPresets().FirstOrDefault(x => x.id == id); + var lgPreset = _serviceManager.LgService?.GetPresets().FirstOrDefault(x => x.id == id); if (lgPreset != null) { _lgPanel?.ApplyLgPreset(lgPreset); @@ -572,11 +533,11 @@ namespace ColorControl { var ps = Marshal.PtrToStructure(m.LParam); - var power = (LgService.WindowsPowerSetting)ps.Data; + var power = (WindowsMonitorPowerSetting)ps.Data; Logger.Debug($"PBT_POWERSETTINGCHANGE: {power}"); - _lgService?.PowerSettingChanged(power); + _powerEventDispatcher.SendEvent(power == WindowsMonitorPowerSetting.Off ? PowerEventDispatcher.Event_MonitorOff : PowerEventDispatcher.Event_MonitorOn); } } @@ -683,10 +644,10 @@ namespace ColorControl Utils.WriteObject(Program.ConfigFilename, _config); } - private void MainForm_Shown(object sender, EventArgs e) + private async void MainForm_Shown(object sender, EventArgs e) { InitSelectedTab(); - CheckForUpdates(); + await CheckForUpdates(); CheckElevationMethod(); } @@ -792,11 +753,11 @@ NOTE: installing the service may cause a User Account Control popup."); } } - if (_nvService != null) + if (_serviceManager.NvService != null) { if (_nvDitherPanel == null) { - _nvDitherPanel = new NvDitherPanel(_nvService); + _nvDitherPanel = new NvDitherPanel(_serviceManager.NvService); tabOptions.Controls.Add(_nvDitherPanel); @@ -854,62 +815,62 @@ NOTE: installing the service may cause a User Account Control popup."); } } - private void TrayMenuItemNv_Click(object sender, EventArgs e) + private async void TrayMenuItemNv_Click(object sender, EventArgs e) { var item = sender as ToolStripMenuItem; var preset = (NvPreset)item.Tag; - _nvPanel?.ApplyNvPreset(preset); + await _nvPanel?.ApplyNvPreset(preset); } - private void TrayMenuItemAmd_Click(object sender, EventArgs e) + private async void TrayMenuItemAmd_Click(object sender, EventArgs e) { var item = sender as ToolStripMenuItem; var preset = (AmdPreset)item.Tag; - _amdPanel?.ApplyAmdPreset(preset); + await _amdPanel?.ApplyAmdPreset(preset); } - private void TrayMenuItemGame_Click(object sender, EventArgs e) + private async void TrayMenuItemGame_Click(object sender, EventArgs e) { var item = sender as ToolStripMenuItem; var preset = (GamePreset)item.Tag; - _gamePanel?.ApplyGamePreset(preset); + await _gamePanel?.ApplyGamePreset(preset); } private void trayIconContextMenu_Popup(object sender, EventArgs e) { - _nvTrayMenu.Visible = _nvService != null; + _nvTrayMenu.Visible = _serviceManager.NvService != null; if (_nvTrayMenu.Visible) { - var presets = _nvService.GetPresets().Where(x => x.applyColorData || x.applyDithering || x.applyHDR || x.applyRefreshRate || x.applyResolution || x.applyDriverSettings); + var presets = _serviceManager.NvService.GetPresets().Where(x => x.applyColorData || x.applyDithering || x.applyHDR || x.applyRefreshRate || x.applyResolution || x.applyDriverSettings); UpdateTrayMenu(_nvTrayMenu, presets, TrayMenuItemNv_Click); } - _amdTrayMenu.Visible = _amdService != null; + _amdTrayMenu.Visible = _serviceManager.AmdService != null; if (_amdTrayMenu.Visible) { - var presets = _amdService.GetPresets().Where(x => x.applyColorData || x.applyDithering || x.applyHDR || x.applyRefreshRate); + var presets = _serviceManager.AmdService.GetPresets().Where(x => x.applyColorData || x.applyDithering || x.applyHDR || x.applyRefreshRate); UpdateTrayMenu(_amdTrayMenu, presets, TrayMenuItemAmd_Click); } - _lgTrayMenu.Visible = _lgService != null; + _lgTrayMenu.Visible = _serviceManager.LgService != null; if (_lgTrayMenu.Visible) { - var presets = _lgService.GetPresets().Where(x => !string.IsNullOrEmpty(x.appId) || x.steps.Any()); + var presets = _serviceManager.LgService.GetPresets().Where(x => !string.IsNullOrEmpty(x.appId) || x.steps.Any()); _lgTrayMenu.DropDownItems.Clear(); UpdateTrayMenu(_lgTrayMenu, presets, TrayMenuItemLg_Click); } - _gameTrayMenu.Visible = _gameService != null; + _gameTrayMenu.Visible = _serviceManager.GameService != null; if (_gameTrayMenu.Visible) { - var presets = _gameService.GetPresets(); + var presets = _serviceManager.GameService.GetPresets(); _gameTrayMenu.DropDownItems.Clear(); @@ -917,12 +878,12 @@ NOTE: installing the service may cause a User Account Control popup."); } } - private void TrayMenuItemLg_Click(object sender, EventArgs e) + private async void TrayMenuItemLg_Click(object sender, EventArgs e) { var item = sender as ToolStripMenuItem; var preset = (LgPreset)item.Tag; - _lgPanel?.ApplyLgPreset(preset); + await _lgPanel?.ApplyLgPreset(preset); } private void LoadLog() @@ -969,12 +930,12 @@ NOTE: installing the service may cause a User Account Control popup."); private void LoadInfo() { - grpNVIDIAInfo.Visible = _nvService != null; + grpNVIDIAInfo.Visible = _serviceManager.NvService != null; } private void btnRefreshNVIDIAInfo_Click(object sender, EventArgs e) { - if (_nvService != null) + if (_serviceManager.NvService != null) { tvNVIDIAInfo.Nodes.Clear(); var displays = Display.GetDisplays(); @@ -987,29 +948,6 @@ NOTE: installing the service may cause a User Account Control popup."); } } - private void btnLGTestPower_Click(object sender, EventArgs e) - { - var text = -@"The TV will now power off. Please wait for the TV to be powered off completely (relay click) and press ENTER to wake it again. -For waking up to work, you need to activate the following setting on the TV: - -Connection > Mobile TV On > Turn on via Wi-Fi - -It will also work over a wired connection. -You can also activate this option by using the Expert-button and selecting Wake-On-LAN > Enabled. - -Do you want to continue?"; - - if (MessageForms.QuestionYesNo(text) == DialogResult.Yes) - { - Utils.WaitForTask(_lgService.PowerOff()); - - MessageForms.InfoOk("Press ENTER to wake the TV."); - - _lgService.WakeSelectedDevice(); - } - } - private void btnSetShortcutScreenSaver_Click(object sender, EventArgs e) { var shortcut = edtBlankScreenSaverShortcut.Text.Trim(); @@ -1075,11 +1013,11 @@ Do you want to continue?"; _amdPanel?.AfterInitialized(); if (_trayIcon.Visible) { - CheckForUpdates(); + var _ = CheckForUpdates(); } } - private void CheckForUpdates() + private async Task CheckForUpdates() { if (!_config.CheckForUpdates || _checkedForUpdates || Debugger.IsAttached) { @@ -1088,7 +1026,7 @@ Do you want to continue?"; _checkedForUpdates = true; - var _ = Utils.GetRestJsonAsync("https://api.github.com/repos/maassoft/colorcontrol/releases/latest", InitHandleCheckForUpdates); + await Utils.GetRestJsonAsync("https://api.github.com/repos/maassoft/colorcontrol/releases/latest", InitHandleCheckForUpdates); } private void InitHandleCheckForUpdates(dynamic latest) @@ -1185,9 +1123,9 @@ Do you want to continue?"; private bool ShortCutExists(string shortcut, int presetId = 0) { return - (_nvService?.GetPresets().Any(x => x.id != presetId && shortcut.Equals(x.shortcut)) ?? false) || - (_amdService?.GetPresets().Any(x => x.id != presetId && shortcut.Equals(x.shortcut)) ?? false) || - (_lgService?.GetPresets().Any(x => x.id != presetId && shortcut.Equals(x.shortcut)) ?? false); + (_serviceManager.NvService?.GetPresets().Any(x => x.id != presetId && shortcut.Equals(x.shortcut)) ?? false) || + (_serviceManager.AmdService?.GetPresets().Any(x => x.id != presetId && shortcut.Equals(x.shortcut)) ?? false) || + (_serviceManager.LgService?.GetPresets().Any(x => x.id != presetId && shortcut.Equals(x.shortcut)) ?? false); } private void chkMinimizeToSystemTray_CheckedChanged(object sender, EventArgs e) @@ -1324,7 +1262,7 @@ Currently ColorControl is {(Utils.IsAdministrator() ? "" : "not ")}running as ad "); } - private void btnStartStopService_Click(object sender, EventArgs e) + private async void btnStartStopService_Click(object sender, EventArgs e) { btnStartStopService.Enabled = false; try @@ -1340,11 +1278,11 @@ Currently ColorControl is {(Utils.IsAdministrator() ? "" : "not ")}running as ad Utils.StopService(); } - var wait = 1000; + var wait = 1500; while (wait > 0) { - Utils.WaitForTask(Task.Delay(100)); + await Task.Delay(100); if (start == Utils.IsServiceRunning()) { @@ -1369,12 +1307,43 @@ Currently ColorControl is {(Utils.IsAdministrator() ? "" : "not ")}running as ad private void MainForm_Click(object sender, EventArgs e) { + //_config.UseDarkMode = !_config.UseDarkMode; + + //SetTheme(_config.UseDarkMode); + + //_powerEventDispatcher.SendEvent(PowerEventDispatcher.Event_Shutdown); //PipeUtils.SendMessage(SvcMessageType.RestartAfterUpdate); //Program.Restart(); //Environment.Exit(0); //InstallUpdate(""); } + private void SetTheme(bool toDark) + { + var settings = new UISettings(); + + var foregroundColorValue = settings.GetColorValue(UIColorType.Foreground); + var isDarkMode = FormUtils.IsColorLight(foregroundColorValue); + + var backroundColorValue = settings.GetColorValue(UIColorType.Background); + + //var toDark = isDarkMode; + + const int DWMWA_USE_IMMERSIVE_DARK_MODE = 20; + var value = toDark ? 1 : 0; + + var result = WinApi.DwmSetWindowAttribute(Handle, DWMWA_USE_IMMERSIVE_DARK_MODE, ref value, 4); + + //var toDark = BackColor == SystemColors.Control; + + BackColor = toDark ? Color.FromArgb(backroundColorValue.R, backroundColorValue.G, backroundColorValue.B) : SystemColors.Control; + ForeColor = toDark ? Color.FromArgb(foregroundColorValue.R, foregroundColorValue.G, foregroundColorValue.B) : SystemColors.ControlText; + + FormUtils.SetControlTheme(this, BackColor, ForeColor); + + WinApi.FlushMenuThemes(); + } + private void chkAutoInstallUpdates_CheckedChanged(object sender, EventArgs e) { if (_initialized) @@ -1432,10 +1401,6 @@ Currently ColorControl is {(Utils.IsAdministrator() ? "" : "not ")}running as ad } } - private void MainForm_KeyDown(object sender, KeyEventArgs e) - { - } - protected override bool ProcessCmdKey(ref Message msg, Keys keyData) { if ((keyData == (Keys.Control | Keys.PageUp) || keyData == (Keys.Control | Keys.PageDown)) && IsShortcutControlFocused()) diff --git a/ColorControl/Native/WinApi.cs b/ColorControl/Native/WinApi.cs index dd27396..2733a90 100644 --- a/ColorControl/Native/WinApi.cs +++ b/ColorControl/Native/WinApi.cs @@ -131,5 +131,23 @@ namespace ColorControl.Native [DllImport("user32.dll", SetLastError = true)] public static extern bool ChangeWindowMessageFilterEx(IntPtr hWnd, uint msg, ChangeWindowMessageFilterExAction action, ref CHANGEFILTERSTRUCT changeInfo); + + [DllImport("uxtheme.dll", CharSet = CharSet.Unicode)] + public static extern int SetWindowTheme(IntPtr hWnd, string pszSubAppName, string pszSubIdList); + + [DllImport("uxtheme.dll", CharSet = CharSet.Unicode, EntryPoint = "#104")] + public static extern int RefreshImmersiveColorPolicyState(); + + [DllImport("uxtheme.dll", CharSet = CharSet.Unicode, EntryPoint = "#133")] + public static extern int AllowDarkModeForWindow(IntPtr hWnd, bool allow); + + [DllImport("uxtheme.dll", CharSet = CharSet.Unicode, EntryPoint = "#135")] + public static extern int SetPreferredAppMode(int appMode); + + [DllImport("uxtheme.dll", EntryPoint = "#136")] + public static extern void FlushMenuThemes(); + + [DllImport("dwmapi.dll", PreserveSig = true)] + public static extern int DwmSetWindowAttribute(IntPtr hwnd, int attr, ref int attrValue, int attrSize); } } diff --git a/ColorControl/Program.cs b/ColorControl/Program.cs index 7a5f05f..fb031c8 100644 --- a/ColorControl/Program.cs +++ b/ColorControl/Program.cs @@ -3,6 +3,7 @@ using ColorControl.Forms; using ColorControl.Services.AMD; using ColorControl.Services.Common; using ColorControl.Services.EventDispatcher; +using ColorControl.Services.GameLauncher; using ColorControl.Services.LG; using ColorControl.Services.NVIDIA; using ColorControl.Svc; @@ -38,15 +39,23 @@ namespace ColorControl private static Mutex _mutex; private static MainForm _mainForm; + [STAThread] // autogenerated + public static void Main(string[] args) + { + // STA + MainAsync(args).GetAwaiter().GetResult(); + } + /// /// The main entry point for the application. /// - [STAThread] - static void Main(string[] args) + //[STAThread] + static async Task MainAsync(string[] args) { DataDir = Utils.GetDataPath(); //Utils.UpdateFiles(@"H:\temp\ColorControl\ColorControl", @"C:\Users\vinni\source\repos\ColorControl\ColorControl\bin\Debug\net6.0-windows10.0.20348.0"); + //Utils.UnZipFile(@"H:\temp\ColorControl\ColorControl.zip", @"H:\temp\ColorControl\temp"); var runAsService = args.Contains("--service") || Utils.IsAdministrator() && Process.GetCurrentProcess().Parent()?.ProcessName?.Equals("services", StringComparison.InvariantCultureIgnoreCase) == true; @@ -62,7 +71,7 @@ namespace ColorControl { AppContext = new AppContext(null, new StartUpParams(), DataDir); - Utils.WaitForTask(RunService(args)); + await RunService(args); return; } @@ -89,7 +98,7 @@ namespace ColorControl try { - if (HandleStartupParams(startUpParams, existingProcess)) + if (await HandleStartupParams(startUpParams, existingProcess)) { return; } @@ -124,9 +133,13 @@ namespace ColorControl // Utils.StartService(); //} + //var result = WinApi.SetPreferredAppMode(1); + //result = WinApi.RefreshImmersiveColorPolicyState(); + Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); - _mainForm = new MainForm(AppContext); + + _mainForm = ServiceProvider.GetRequiredService(); Application.Run(_mainForm); if (Debugger.IsAttached && !IsRestarting) @@ -204,7 +217,7 @@ namespace ColorControl Utils.UseDedicatedElevatedProcess = Config.UseDedicatedElevatedProcess; } - public static bool HandleStartupParams(StartUpParams startUpParams, Process existingProcess) + public static async Task HandleStartupParams(StartUpParams startUpParams, Process existingProcess) { if (startUpParams.ActivateChromeFontFix || startUpParams.DeactivateChromeFontFix) { @@ -289,14 +302,9 @@ namespace ColorControl Utils.OpenConsole(); Console.WriteLine($"Executing LG-preset '{startUpParams.LgPresetName}'..."); - var task = LgService.ExecutePresetAsync(startUpParams.LgPresetName); + await LgService.ExecutePresetAsync(startUpParams.LgPresetName); - var taskResult = Utils.WaitForTask(task); - - if (taskResult) - { - Console.WriteLine("Done."); - } + Console.WriteLine("Done."); result = true; } @@ -306,12 +314,9 @@ namespace ColorControl Utils.OpenConsole(); Console.WriteLine($"Executing NVIDIA-preset '{startUpParams.NvidiaPresetIdOrName}'..."); - var taskResult = NvService.ExecutePresetAsync(startUpParams.NvidiaPresetIdOrName); + await NvService.ExecutePresetAsync(startUpParams.NvidiaPresetIdOrName); - if (taskResult) - { - Console.WriteLine("Done."); - } + Console.WriteLine("Done."); result = true; } @@ -321,12 +326,9 @@ namespace ColorControl Utils.OpenConsole(); Console.WriteLine($"Executing AMD-preset '{startUpParams.AmdPresetIdOrName}'..."); - var taskResult = AmdService.ExecutePresetAsync(startUpParams.AmdPresetIdOrName); + await AmdService.ExecutePresetAsync(startUpParams.AmdPresetIdOrName); - if (taskResult) - { - Console.WriteLine("Done."); - } + Console.WriteLine("Done."); result = true; } @@ -355,8 +357,11 @@ namespace ColorControl //services.AddSingleton(); services.RegisterSharedServices(); services.AddSingleton(); + services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); }); } private static async Task RunService(string[] args) diff --git a/ColorControl/Services/AMD/AmdPanel.cs b/ColorControl/Services/AMD/AmdPanel.cs index c6813b1..ad50e83 100644 --- a/ColorControl/Services/AMD/AmdPanel.cs +++ b/ColorControl/Services/AMD/AmdPanel.cs @@ -121,10 +121,10 @@ namespace ColorControl.Services.AMD public void AfterInitialized() { - ApplyAmdPresetOnStartup(); + var _ = ApplyAmdPresetOnStartup(); } - private void ApplyAmdPresetOnStartup(int attempts = 5) + private async Task ApplyAmdPresetOnStartup(int attempts = 5) { var startUpParams = AppContext.CurrentContext.StartUpParams; var presetIdOrName = !string.IsNullOrEmpty(startUpParams.AmdPresetIdOrName) ? startUpParams.AmdPresetIdOrName : _config.AmdPresetId_ApplyOnStartup.ToString(); @@ -143,18 +143,15 @@ namespace ColorControl.Services.AMD { if (_amdService.HasDisplaysAttached()) { - ApplyAmdPreset(preset); + await ApplyAmdPreset(preset); } else { attempts--; if (attempts > 0) { - Task.Run(async () => - { - await Task.Delay(2000); - BeginInvoke(() => ApplyAmdPresetOnStartup(attempts)); - }); + await Task.Delay(2000); + await ApplyAmdPresetOnStartup(attempts); } } } @@ -226,13 +223,13 @@ namespace ColorControl.Services.AMD AddOrUpdateItemAmd(); } - private void ApplySelectedAmdPreset() + private async Task ApplySelectedAmdPreset() { var preset = GetSelectedAmdPreset(); - ApplyAmdPreset(preset); + await ApplyAmdPreset(preset); } - internal bool ApplyAmdPreset(AmdPreset preset) + internal async Task ApplyAmdPreset(AmdPreset preset) { if (preset == null || _amdService == null) { @@ -240,7 +237,7 @@ namespace ColorControl.Services.AMD } try { - var result = _amdService.ApplyPreset(preset); + var result = await _amdService.ApplyPreset(preset); if (!result) { throw new Exception("Error while applying AMD preset. At least one setting could not be applied. Check the log for details."); @@ -255,9 +252,9 @@ namespace ColorControl.Services.AMD } } - private void btnApplyAmd_Click(object sender, EventArgs e) + private async void btnApplyAmd_Click(object sender, EventArgs e) { - ApplySelectedAmdPreset(); + await ApplySelectedAmdPreset(); } private void btnChangeAmd_Click(object sender, EventArgs e) diff --git a/ColorControl/Services/AMD/AmdService.cs b/ColorControl/Services/AMD/AmdService.cs index cd8221f..d70b437 100644 --- a/ColorControl/Services/AMD/AmdService.cs +++ b/ColorControl/Services/AMD/AmdService.cs @@ -5,6 +5,7 @@ using Microsoft.Extensions.DependencyInjection; using System; using System.Collections.Generic; using System.Linq; +using System.Threading.Tasks; using System.Windows.Forms; namespace ColorControl.Services.AMD @@ -24,7 +25,7 @@ namespace ColorControl.Services.AMD LoadPresets(); } - public static bool ExecutePresetAsync(string idOrName) + public static async Task ExecutePresetAsync(string idOrName) { try { @@ -32,7 +33,7 @@ namespace ColorControl.Services.AMD var service = new AmdService(appContextProvider); - var result = service.ApplyPreset(idOrName); + var result = await service.ApplyPreset(idOrName); if (!result) { @@ -98,12 +99,12 @@ namespace ColorControl.Services.AMD return _currentDisplay; } - public bool ApplyPreset(string idOrName) + public async Task ApplyPreset(string idOrName) { var preset = GetPresetByIdOrName(idOrName); if (preset != null) { - return ApplyPreset(preset); + return await ApplyPreset(preset); } else { @@ -111,7 +112,7 @@ namespace ColorControl.Services.AMD } } - public override bool ApplyPreset(AmdPreset preset) + public override async Task ApplyPreset(AmdPreset preset) { SetCurrentDisplay(preset); diff --git a/ColorControl/Services/Common/ServiceBase.cs b/ColorControl/Services/Common/ServiceBase.cs index 4073db3..5dba08e 100644 --- a/ColorControl/Services/Common/ServiceBase.cs +++ b/ColorControl/Services/Common/ServiceBase.cs @@ -3,6 +3,7 @@ using System; using System.Collections.Generic; using System.IO; using System.Linq; +using System.Threading.Tasks; namespace ColorControl.Services.Common { @@ -60,7 +61,7 @@ namespace ColorControl.Services.Common return preset; } - public abstract bool ApplyPreset(T preset); + public abstract Task ApplyPreset(T preset); public T GetLastAppliedPreset() { diff --git a/ColorControl/Services/Common/ServiceManager.cs b/ColorControl/Services/Common/ServiceManager.cs index 2ba05c2..b36eb7c 100644 --- a/ColorControl/Services/Common/ServiceManager.cs +++ b/ColorControl/Services/Common/ServiceManager.cs @@ -1,27 +1,63 @@ -namespace ColorControl.Services.Common +using ColorControl.Common; +using ColorControl.Services.AMD; +using ColorControl.Services.GameLauncher; +using ColorControl.Services.LG; +using ColorControl.Services.NVIDIA; +using System; +using System.Linq; +using System.Threading.Tasks; + +namespace ColorControl.Services.Common { - class ServiceManager + public class ServiceManager { - public static ServiceManager Instance + internal NvService NvService { get; set; } + internal LgService LgService { get; set; } + internal AmdService AmdService { get; set; } + internal GameService GameService { get; set; } + + public async Task HandleExternalServiceAsync(string serviceName, string[] parameters) { - get + if (string.IsNullOrEmpty(serviceName) || parameters.Length == 0) { - if (_instance == null) - { - _instance = new ServiceManager(); - } - - return _instance; + return false; } + + if (NvService != null && serviceName.Equals("NvPreset", StringComparison.OrdinalIgnoreCase)) + { + return await NvService.ApplyPreset(parameters[0]); + } + if (NvService != null && serviceName.Equals("GsyncEnabled", StringComparison.OrdinalIgnoreCase)) + { + return NvService.IsGsyncEnabled(); + } + if (AmdService != null && serviceName.Equals("AmdPreset", StringComparison.OrdinalIgnoreCase)) + { + return await AmdService.ApplyPreset(parameters[0]); + } + if (LgService != null && serviceName.Equals("LgPreset", StringComparison.OrdinalIgnoreCase)) + { + await LgService.ApplyPreset(parameters[0]); + + return true; + } + + if (serviceName.Equals("StartProgram", StringComparison.OrdinalIgnoreCase)) + { + Utils.StartProcess(parameters[0], parameters.Length > 1 ? string.Join(" ", parameters.Skip(1)) : null, setWorkingDir: true); + + return true; + } + + return false; } - private static ServiceManager _instance { get; set; } - //private List> _services = new(); - - public void Initialize() + public void Save() { - + NvService?.GlobalSave(); + AmdService?.GlobalSave(); + LgService?.GlobalSave(); + GameService?.GlobalSave(); } - } } diff --git a/ColorControl/Services/EventDispatcher/PowerEventDispatcher.cs b/ColorControl/Services/EventDispatcher/PowerEventDispatcher.cs index 0728997..7823315 100644 --- a/ColorControl/Services/EventDispatcher/PowerEventDispatcher.cs +++ b/ColorControl/Services/EventDispatcher/PowerEventDispatcher.cs @@ -1,26 +1,77 @@ using Microsoft.Win32; +using System; namespace ColorControl.Services.EventDispatcher { - public class PowerEventDispatcher : EventDispatcher + public enum PowerOnOffState + { + None = 0, + StartUp = 1, + Resume = 2, + ScreenSaver = 3, + ShutDown = 4, + StandBy = 5, + MonitorOff = 6, + MonitorOn = 7 + } + + internal enum WindowsMonitorPowerSetting + { + Off = 0, + On = 1, + Dimmed = 2 + } + + public class PowerStateChangedEventArgs : EventArgs + { + public PowerOnOffState State { get; private set; } + + public PowerStateChangedEventArgs(PowerOnOffState state) + { + State = state; + } + } + + public class PowerEventDispatcher : EventDispatcher { public const string Event_Suspend = "Suspend"; public const string Event_Resume = "Resume"; + public const string Event_Shutdown = "Shutdown"; + public const string Event_MonitorOff = "MonitorOff"; + public const string Event_MonitorOn = "MonitorOn"; public PowerEventDispatcher() { SystemEvents.PowerModeChanged += OnPowerModeChanged; } + public void SendEvent(string eventName) + { + var state = eventName switch + { + Event_Shutdown => PowerOnOffState.ShutDown, + Event_MonitorOff => PowerOnOffState.MonitorOff, + Event_MonitorOn => PowerOnOffState.MonitorOn, + _ => PowerOnOffState.None + }; + + if (state == PowerOnOffState.None) + { + return; + } + + DispatchEvent(eventName, new PowerStateChangedEventArgs(state)); + } + private void OnPowerModeChanged(object sender, PowerModeChangedEventArgs e) { if (e.Mode == PowerModes.Suspend) { - DispatchEvent(Event_Suspend, e); + DispatchEvent(Event_Suspend, new PowerStateChangedEventArgs(PowerOnOffState.StandBy)); } else if (e.Mode == PowerModes.Resume) { - DispatchEvent(Event_Resume, e); + DispatchEvent(Event_Resume, new PowerStateChangedEventArgs(PowerOnOffState.Resume)); } } } diff --git a/ColorControl/Services/EventDispatcher/ProcessEventDispatcher.cs b/ColorControl/Services/EventDispatcher/ProcessEventDispatcher.cs index 41219bc..5e4cf87 100644 --- a/ColorControl/Services/EventDispatcher/ProcessEventDispatcher.cs +++ b/ColorControl/Services/EventDispatcher/ProcessEventDispatcher.cs @@ -36,9 +36,9 @@ namespace ColorControl.Services.EventDispatcher { IsRunning = true; - Task.Run(async () => await CheckProcesses()); + //Task.Run(async () => await CheckProcesses()); - //var _ = CheckProcesses(); + var _ = CheckProcesses(); } private async Task CheckProcesses() @@ -50,7 +50,6 @@ namespace ColorControl.Services.EventDispatcher //startWatch.Start(); MonitorContext ??= new ProcessChangedEventArgs(); - //Process[] lastProcesses = null; while (IsRunning) { diff --git a/ColorControl/Services/GameLauncher/GamePanel.cs b/ColorControl/Services/GameLauncher/GamePanel.cs index 9b48f9f..0880542 100644 --- a/ColorControl/Services/GameLauncher/GamePanel.cs +++ b/ColorControl/Services/GameLauncher/GamePanel.cs @@ -13,6 +13,7 @@ using System.ComponentModel; using System.Diagnostics; using System.IO; using System.Linq; +using System.Threading.Tasks; using System.Windows.Forms; namespace ColorControl.Services.GameLauncher @@ -102,13 +103,13 @@ namespace ColorControl.Services.GameLauncher } } - private void ApplySelectedGamePreset() + private async Task ApplySelectedGamePreset() { var preset = GetSelectedGamePreset(); - ApplyGamePreset(preset); + await ApplyGamePreset(preset); } - internal bool ApplyGamePreset(GamePreset preset) + internal async Task ApplyGamePreset(GamePreset preset) { if (preset == null || _gameService == null) { @@ -116,7 +117,7 @@ namespace ColorControl.Services.GameLauncher } try { - var result = _gameService.ApplyPreset(preset, Program.AppContext); + var result = await _gameService.ApplyPreset(preset, Program.AppContext); if (!result) { throw new Exception("Error while applying Game-preset. At least one setting could not be applied. Check the log for details."); @@ -158,14 +159,14 @@ namespace ColorControl.Services.GameLauncher } } - private void lvGamePresets_DoubleClick(object sender, EventArgs e) + private async void lvGamePresets_DoubleClick(object sender, EventArgs e) { - ApplySelectedGamePreset(); + await ApplySelectedGamePreset(); } - private void btnGameLaunch_Click(object sender, EventArgs e) + private async void btnGameLaunch_Click(object sender, EventArgs e) { - ApplySelectedGamePreset(); + await ApplySelectedGamePreset(); } private void btnGameClone_Click(object sender, EventArgs e) diff --git a/ColorControl/Services/GameLauncher/GameService.cs b/ColorControl/Services/GameLauncher/GameService.cs index 85b498d..38d9d50 100644 --- a/ColorControl/Services/GameLauncher/GameService.cs +++ b/ColorControl/Services/GameLauncher/GameService.cs @@ -1,7 +1,5 @@ using ColorControl.Common; using ColorControl.Services.Common; -using Microsoft.Extensions.DependencyInjection; -using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; @@ -17,36 +15,12 @@ namespace ColorControl.Services.GameLauncher protected override string PresetsBaseFilename => "GamePresets.json"; - private Func _externalServiceHandler; + private ServiceManager _serviceManager; - public GameService(AppContextProvider appContextProvider, Func externalServiceHandler = null) : base(appContextProvider) + public GameService(AppContextProvider appContextProvider, ServiceManager serviceManager) : base(appContextProvider) { LoadPresets(); - _externalServiceHandler = externalServiceHandler; - } - - public static bool ExecutePresetAsync(string idOrName) - { - try - { - var appContextProvider = Program.ServiceProvider.GetRequiredService(); - - var service = new GameService(appContextProvider); - - var result = service.ApplyPreset(idOrName); - - if (!result) - { - Console.WriteLine("Preset not found or error while executing."); - } - - return result; - } - catch (Exception ex) - { - Console.WriteLine("Error executing preset: " + ex.ToLogString()); - return false; - } + _serviceManager = serviceManager; } protected override List GetDefaultPresets() @@ -64,12 +38,12 @@ namespace ColorControl.Services.GameLauncher SavePresets(); } - public bool ApplyPreset(string idOrName) + public async Task ApplyPreset(string idOrName) { var preset = GetPresetByIdOrName(idOrName); if (preset != null) { - return ApplyPreset(preset, Program.AppContext); + return await ApplyPreset(preset, Program.AppContext); } else { @@ -77,16 +51,16 @@ namespace ColorControl.Services.GameLauncher } } - public override bool ApplyPreset(GamePreset preset) + public override async Task ApplyPreset(GamePreset preset) { - return ApplyPreset(preset, Program.AppContext); + return await ApplyPreset(preset, Program.AppContext); } - public bool ApplyPreset(GamePreset preset, AppContext appContext) + public async Task ApplyPreset(GamePreset preset, AppContext appContext) { var result = true; - ExecuteSteps(preset.PreLaunchSteps); + await ExecuteSteps(preset.PreLaunchSteps); Process process = null; @@ -95,11 +69,11 @@ namespace ColorControl.Services.GameLauncher process = Utils.StartProcess(preset.Path, preset.Parameters, setWorkingDir: true, elevate: preset.RunAsAdministrator, affinityMask: preset.ProcessAffinityMask, priorityClass: preset.ProcessPriorityClass); } - ExecuteSteps(preset.PostLaunchSteps); + await ExecuteSteps(preset.PostLaunchSteps); if (process != null && preset.FinalizeSteps?.Any() == true) { - var _ = ExecuteFinalizationStepsAsync(process, preset.FinalizeSteps); + await ExecuteFinalizationStepsAsync(process, preset.FinalizeSteps); } _lastAppliedPreset = preset; @@ -113,10 +87,10 @@ namespace ColorControl.Services.GameLauncher { await process.WaitForExitAsync(); - ExecuteSteps(finalizeSteps); + await ExecuteSteps(finalizeSteps); } - private void ExecuteSteps(List steps) + private async Task ExecuteSteps(List steps) { if (steps?.Any() != true) { @@ -149,9 +123,9 @@ namespace ColorControl.Services.GameLauncher var handled = false; - if (_externalServiceHandler != null && parameters != null) + if (parameters != null) { - handled = _externalServiceHandler(key, parameters); + handled = await _serviceManager.HandleExternalServiceAsync(key, parameters); } if (!handled) @@ -160,7 +134,7 @@ namespace ColorControl.Services.GameLauncher if (delay > 0) { - Utils.WaitForTask(Task.Delay(delay)); + await Task.Delay(delay); } } diff --git a/ColorControl/Services/LG/LgDevice.cs b/ColorControl/Services/LG/LgDevice.cs index d9e3c14..b0518ee 100644 --- a/ColorControl/Services/LG/LgDevice.cs +++ b/ColorControl/Services/LG/LgDevice.cs @@ -1,5 +1,7 @@ using ColorControl.Common; +using ColorControl.Services.Common; using LgTv; +using Microsoft.Extensions.DependencyInjection; using Newtonsoft.Json; using System; using System.Collections.Generic; @@ -13,7 +15,7 @@ namespace ColorControl.Services.LG { public class InvokableAction { - public Func, bool> Function { get; set; } + public Func, Task> AsyncFunction { get; set; } public string Name { get; set; } public Type EnumType { get; set; } public decimal MinValue { get; set; } @@ -66,7 +68,6 @@ namespace ColorControl.Services.LG } protected static readonly NLog.Logger Logger = NLog.LogManager.GetCurrentClassLogger(); - public static Func ExternalServiceHandler; public static List DefaultActionsOnGameBar = new() { "backlight", "contrast", "brightness", "color" }; public string Name { get; private set; } @@ -82,7 +83,10 @@ namespace ColorControl.Services.LG public bool PowerOffOnStandby { get; set; } public bool PowerOffOnScreenSaver { get; set; } public int ScreenSaverMinimalDuration { get; set; } + public bool TurnScreenOffOnScreenSaver { get; set; } + public bool HandleManualScreenSaver { get; set; } public bool PowerOnAfterScreenSaver { get; set; } + public bool TurnScreenOnAfterScreenSaver { get; set; } public bool PowerOnAfterManualPowerOff { get; set; } public bool PowerOnByWindows { get; set; } public bool PowerOffByWindows { get; set; } @@ -148,12 +152,17 @@ namespace ColorControl.Services.LG [JsonIgnore] private Timer _powerOffTimer; + [JsonIgnore] + private ServiceManager _serviceManager; + [JsonConstructor] public LgDevice(string name, string ipAddress, string macAddress, bool isCustom = true, bool isDummy = false) { PictureSettings = new LgDevicePictureSettings(); ActionsOnGameBar = new List(DefaultActionsOnGameBar); + _serviceManager = Program.ServiceProvider.GetRequiredService(); + Name = name; IpAddress = ipAddress; MacAddress = macAddress; @@ -161,7 +170,7 @@ namespace ColorControl.Services.LG IsDummy = isDummy; TriggersEnabled = true; - AddInvokableAction("WOL", new Func, bool>(WakeAction)); + AddInvokableAction("WOL", WakeAction); AddGenericPictureAction("backlight", minValue: 0, maxValue: 100); AddGenericPictureAction("brightness", minValue: 0, maxValue: 100, title: "Brightness/Black Level"); AddGenericPictureAction("contrast", minValue: 0, maxValue: 100); @@ -238,8 +247,8 @@ namespace ColorControl.Services.LG AddGenericPictureAction("whiteBalanceGreen", minValue: -50, maxValue: 50, numberOfValues: 22); AddGenericPictureAction("whiteBalanceRed", minValue: -50, maxValue: 50, numberOfValues: 22); //AddGenericPictureAction("wb20PointsGammaValue", minValue: -50, maxValue: 50); - AddInvokableAction("turnScreenOff", new Func, bool>(TurnScreenOffAction)); - AddInvokableAction("turnScreenOn", new Func, bool>(TurnScreenOnAction)); + AddInvokableAction("turnScreenOff", TurnScreenOffAction); + AddInvokableAction("turnScreenOn", TurnScreenOnAction); AddInternalPresetAction(new LgPreset("InStart", "com.webos.app.factorywin", new[] { "0", "4", "1", "3" }, new { id = "executeFactory", irKey = "inStart" })); AddInternalPresetAction(new LgPreset("EzAdjust", "com.webos.app.factorywin", new[] { "0", "4", "1", "3" }, new { id = "executeFactory", irKey = "ezAdjust" })); @@ -266,12 +275,14 @@ namespace ColorControl.Services.LG ClearPowerOffTask(); } - private void AddInvokableAction(string name, Func, bool> function) + private void AddInvokableAction(string name, Func, Task> function) { var action = new InvokableAction { Name = name, - Function = function + AsyncFunction = function, + Category = "misc", + Title = name }; _invokableActions.Add(action); @@ -293,7 +304,7 @@ namespace ColorControl.Services.LG var action = new InvokableAction { Name = name, - Function = new Func, bool>(GenericPictureAction), + AsyncFunction = GenericPictureAction, EnumType = type, MinValue = minValue, MaxValue = maxValue, @@ -311,7 +322,7 @@ namespace ColorControl.Services.LG var action = new InvokableAction { Name = name, - Function = new Func, bool>(GenericDeviceConfigAction), + AsyncFunction = GenericDeviceConfigAction, EnumType = type, Title = title == null ? Utils.FirstCharUpperCase(name) : title }; @@ -324,7 +335,7 @@ namespace ColorControl.Services.LG var action = new InvokableAction { Name = name, - Function = new Func, bool>(GenericSetConfigAction), + AsyncFunction = GenericSetConfigAction, EnumType = type, Title = title == null ? Utils.FirstCharUpperCase(name) : title, Category = "Config", @@ -507,7 +518,7 @@ namespace ColorControl.Services.LG PoweredOffBy = PoweredOffViaApp ? PowerOffSource.App : PowerOffSource.Manually; } } - else + else if (CurrentState != PowerState.Screen_Off) { PoweredOffBy = PoweredOffViaApp ? PowerOffSource.App : PowerOffSource.Manually; } @@ -542,7 +553,7 @@ namespace ColorControl.Services.LG return !_lgTvApi?.ConnectionClosed ?? false; } - internal void DisposeConnection() + private void DisposeConnection() { if (_lgTvApi != null) { @@ -655,7 +666,7 @@ namespace ColorControl.Services.LG { var keySpec = step.Split(':'); - var delay = 0; + var delay = 10; var key = step; if (keySpec.Length == 2) { @@ -679,23 +690,20 @@ namespace ColorControl.Services.LG var action = _invokableActions.FirstOrDefault(a => a.Name.Equals(key, StringComparison.OrdinalIgnoreCase)); if (action != null) { - ExecuteAction(action, parameters); + await ExecuteActionAsync(action, parameters); executeKey = false; } - if (ExternalServiceHandler != null && parameters != null) + if (parameters != null && await _serviceManager.HandleExternalServiceAsync(key, parameters)) { - if (ExternalServiceHandler(key, parameters)) - { - executeKey = false; - } + executeKey = false; } if (executeKey) { mouse ??= await api.GetMouse(); - SendKey(mouse, key); - delay = delay == 0 ? 180 : delay; + await SendKey(mouse, key); + delay = delay == 0 ? 100 : delay; } if (delay > 0) @@ -705,9 +713,9 @@ namespace ColorControl.Services.LG } } - public void ExecuteAction(InvokableAction action, string[] parameters) + public async Task ExecuteActionAsync(InvokableAction action, string[] parameters) { - var function = action.Function; + var function = action.AsyncFunction; if (function == null) { return; @@ -721,14 +729,14 @@ namespace ColorControl.Services.LG { "category", action.Category } }; - function(keyValues); + await function(keyValues); return; } - function(null); + await function(null); } - private void SendKey(LgWebOsMouseService mouse, string key) + private async Task SendKey(LgWebOsMouseService mouse, string key) { key = key.ToUpper(); if (key.Length >= 1 && int.TryParse(key[0].ToString(), out _)) @@ -736,7 +744,7 @@ namespace ColorControl.Services.LG key = "_" + key; } var button = (ButtonType)Enum.Parse(typeof(ButtonType), key); - mouse.SendButton(button); + await mouse.SendButton(button); } public async Task GetMouseAsync() @@ -754,16 +762,6 @@ namespace ColorControl.Services.LG } } - private void CheckConnection() - { - var task = CheckConnectionAsync(); - - if (task.Status != TaskStatus.RanToCompletion) - { - throw new InvalidOperationException("Not connected"); - } - } - public async Task> GetApps(bool force = false) { if (!force) @@ -780,6 +778,46 @@ namespace ColorControl.Services.LG return await _lgTvApi.GetApps(force); } + public async Task PerformActionOnScreenSaver() + { + if (!IsPowerOffAllowed()) + { + return true; + } + + if (TurnScreenOffOnScreenSaver) + { + Logger.Debug("Turning screen off on screen saver"); + await _lgTvApi.TurnScreenOff(); + + return true; + } + + Logger.Debug($"Device {Name} is now powering off due to delayed screensaver task"); + + return await PowerOff(true, false); + } + + public async Task PerformActionAfterScreenSaver(int powerOnRetries) + { + if (TurnScreenOffOnScreenSaver && IsConnected()) + { + if (TurnScreenOnAfterScreenSaver) + { + try + { + Logger.Debug("Turning screen on after screen saver"); + await _lgTvApi.TurnScreenOn(); + } + catch (Exception) { } + } + + return true; + } + + return await WakeAndConnectWithRetries(powerOnRetries); + } + internal async Task PowerOff(bool checkHdmi = false, bool reconnect = true) { if (!await Connected(reconnect) || CurrentState != PowerState.Active) @@ -787,9 +825,8 @@ namespace ColorControl.Services.LG return false; } - if (checkHdmi && CurrentAppId != null && HDMIPortNumber != 0 && !CurrentAppId.EndsWith($".hdmi{HDMIPortNumber}", StringComparison.InvariantCulture)) + if (checkHdmi && !IsPowerOffAllowed()) { - Logger.Debug($"[{Name}] PowerOff is ignored because current app {CurrentAppId} does not match configured HDMI port {HDMIPortNumber}"); return true; } @@ -798,7 +835,7 @@ namespace ColorControl.Services.LG try { - await _lgTvApi.TurnOff().WaitAsync(TimeSpan.FromSeconds(2)); + await _lgTvApi.TurnOff().WaitAsync(TimeSpan.FromSeconds(2)).ConfigureAwait(true); } catch (TimeoutException ex) { @@ -808,6 +845,17 @@ namespace ColorControl.Services.LG return true; } + public bool IsPowerOffAllowed() + { + if (CurrentAppId != null && HDMIPortNumber != 0 && !CurrentAppId.EndsWith($".hdmi{HDMIPortNumber}", StringComparison.InvariantCulture)) + { + Logger.Debug($"[{Name}] PowerOff/ScreenOff is ignored because current app {CurrentAppId} does not match configured HDMI port {HDMIPortNumber}"); + return false; + } + + return true; + } + internal async Task TestConnection(int retries = 1) { if (!await Connected(true, retries)) @@ -994,34 +1042,32 @@ namespace ColorControl.Services.LG return await _lgTvApi.GetSystemSettings2("picture"); } - private bool WakeAction(Dictionary parameters) + private async Task WakeAction(Dictionary _) { return Wake(); } - private bool TurnScreenOffAction(Dictionary parameters) + private async Task TurnScreenOffAction(Dictionary _) { - CheckConnection(); + await CheckConnectionAsync(); - var task = _lgTvApi.TurnScreenOff(); - Utils.WaitForTask(task); + await _lgTvApi.TurnScreenOff(); return true; } - private bool TurnScreenOnAction(Dictionary parameters) + private async Task TurnScreenOnAction(Dictionary _) { - CheckConnection(); + await CheckConnectionAsync(); - var task = _lgTvApi.TurnScreenOn(); - Utils.WaitForTask(task); + await _lgTvApi.TurnScreenOn(); return true; } - private bool GenericPictureAction(Dictionary parameters) + private async Task GenericPictureAction(Dictionary parameters) { - CheckConnection(); + await CheckConnectionAsync(); var settingName = parameters["name"].ToString(); var stringValues = parameters["value"] as string[]; @@ -1031,17 +1077,16 @@ namespace ColorControl.Services.LG { value = stringValues.Select(s => int.Parse(s)).ToArray(); } - var task = _lgTvApi.SetSystemSettings(settingName, value, category); - Utils.WaitForTask(task); + await _lgTvApi.SetSystemSettings(settingName, value, category); UpdateCurrentValueOfAction(settingName, value.ToString()); return true; } - private bool GenericDeviceConfigAction(Dictionary parameters) + private async Task GenericDeviceConfigAction(Dictionary parameters) { - CheckConnection(); + await CheckConnectionAsync(); var id = parameters["name"].ToString().Replace("_icon", string.Empty); var stringValues = parameters["value"] as string[]; @@ -1049,22 +1094,20 @@ namespace ColorControl.Services.LG var description = Utils.GetDescriptionByEnumName(value); - var task = _lgTvApi.SetDeviceConfig(id, value, description); - Utils.WaitForTask(task); + await _lgTvApi.SetDeviceConfig(id, value, description); return true; } - private bool GenericSetConfigAction(Dictionary parameters) + private async Task GenericSetConfigAction(Dictionary parameters) { - CheckConnection(); + await CheckConnectionAsync(); var key = parameters["name"].ToString(); var values = parameters["value"] as object[]; var value = values[0]; - var task = _lgTvApi.SetConfig(key, value); - Utils.WaitForTask(task); + await _lgTvApi.SetConfig(key, value); return true; } @@ -1112,15 +1155,7 @@ namespace ColorControl.Services.LG { ClearPowerOffTask(); - Logger.Debug($"Device {Name} is now powering off due to delayed screensaver task"); - - var x = PowerOff(true, false); - - //Task.Run(async () => - //{ - // // Do not force reconnect here (MessageWebSocket issues) - // await PowerOff(true, false); - //}); + var x = PerformActionOnScreenSaver(); } } } diff --git a/ColorControl/Services/LG/LgGameBar.cs b/ColorControl/Services/LG/LgGameBar.cs index 412d556..bec220b 100644 --- a/ColorControl/Services/LG/LgGameBar.cs +++ b/ColorControl/Services/LG/LgGameBar.cs @@ -140,6 +140,12 @@ namespace ColorControl.Services.LG _settingChanged = false; return; } + + if (!Visible) + { + return; + } + BeginInvoke(new Action(UpdateValues)); } @@ -275,7 +281,7 @@ namespace ColorControl.Services.LG Hide(); } - private void tbTrackBar_Scroll(object sender, EventArgs e) + private async void tbTrackBar_Scroll(object sender, EventArgs e) { _settingChanged = true; ResetAutoHide(); @@ -283,8 +289,7 @@ namespace ColorControl.Services.LG var trackBar = sender as TrackBar; var setting = (TbSetting)trackBar.Tag; - var value = string.Empty; - + string value; if (setting.EnumType == null) { value = trackBar.Value.ToString(); @@ -295,7 +300,7 @@ namespace ColorControl.Services.LG value = enumValue.ToString(); } - _lgDevice.SetSystemSettings(setting.Name, value).ConfigureAwait(false); + await _lgDevice.SetSystemSettings(setting.Name, value); if (_toolTip != null) { diff --git a/ColorControl/Services/LG/LgPanel.cs b/ColorControl/Services/LG/LgPanel.cs index 25bb6a5..9890be1 100644 --- a/ColorControl/Services/LG/LgPanel.cs +++ b/ColorControl/Services/LG/LgPanel.cs @@ -231,11 +231,11 @@ namespace ColorControl.Services.LG } } - private void btnApplyLg_Click(object sender, EventArgs e) + private async void btnApplyLg_Click(object sender, EventArgs e) { var preset = GetSelectedLgPreset(); - ApplyLgPreset(preset); + await ApplyLgPreset(preset); } private void btnSetShortcutLg_Click(object sender, EventArgs e) @@ -463,23 +463,14 @@ namespace ColorControl.Services.LG AddOrUpdateItemLg(_lgService.CreateNewPreset()); } - internal void ApplyLgPreset(LgPreset preset, bool reconnect = false, bool wait = false) + internal async Task ApplyLgPreset(LgPreset preset, bool reconnect = false) { if (preset == null) { return; } - var applyTask = _lgService.ApplyPreset(preset, reconnect).ContinueWith((task) => BeginInvoke(() => LgPresetApplied(task))); - if (wait) - { - Utils.WaitForTask(applyTask); - } - } - - private void LgPresetApplied(Task task) - { - var result = task.Result; + var result = await _lgService.ApplyPreset(preset, reconnect); if (!result) { MessageForms.WarningOk("Could not apply the preset (entirely). Check the log for details."); @@ -516,10 +507,10 @@ namespace ColorControl.Services.LG ApplySelectedLgPreset(); } - private void ApplySelectedLgPreset() + private async void ApplySelectedLgPreset() { var preset = GetSelectedLgPreset(); - ApplyLgPreset(preset); + await ApplyLgPreset(preset); } private void btnLgAddButton_Click(object sender, EventArgs e) @@ -541,12 +532,14 @@ namespace ColorControl.Services.LG var value = ShowLgActionForm(action); + var text = action.Name; + if (!string.IsNullOrEmpty(value)) { - var text = $"{action.Name}({value})"; - - FormUtils.AddStepToTextBox(edtStepsLg, text); + text += $"({value})"; } + + FormUtils.AddStepToTextBox(edtStepsLg, text); } private string ShowLgActionForm(LgDevice.InvokableAction action) @@ -736,7 +729,7 @@ You can also activate this option by using the Expert-button and selecting Wake- } } - private void btnLgAddDevice_Click(object sender, EventArgs e) + private async void btnLgAddDevice_Click(object sender, EventArgs e) { var values = MessageForms.ShowDialog("Add tv", new[] { "Name", "Ip-address", "MAC-address" }, ValidateAddDevice); if (values.Any()) @@ -749,9 +742,7 @@ You can also activate this option by using the Expert-button and selecting Wake- Enabled = false; try { - var task = device.TestConnection(); - - result = Utils.WaitForTask(task); + await device.TestConnection(); } finally { @@ -866,7 +857,7 @@ Do you want to continue?" const string gameBarName = "miGameBar"; - var expertActions = actions.Where(a => a.EnumType != null || a.MaxValue > a.MinValue).ToList(); + var expertActions = actions.Where(a => a.EnumType != null || a.MaxValue > a.MinValue || a.AsyncFunction != null).ToList(); var categories = expertActions.Select(a => a.Category ?? "misc").Where(c => !string.IsNullOrEmpty(c)).Distinct(); @@ -956,7 +947,7 @@ Do you want to continue?" mnuLgExpert.Show(btnLgExpert, btnLgExpert.PointToClient(Cursor.Position)); } - private void btnLgExpertColorGamut_Click(object sender, EventArgs e) + private async void btnLgExpertColorGamut_Click(object sender, EventArgs e) { var item = sender as ToolStripItem; var action = item.Tag as LgDevice.InvokableAction; @@ -970,7 +961,7 @@ Do you want to continue?" try { - _lgService.SelectedDevice?.ExecuteAction(action, new[] { value }); + await _lgService.SelectedDevice?.ExecuteActionAsync(action, new[] { value }); } catch (InvalidOperationException ex) { @@ -980,7 +971,7 @@ Do you want to continue?" } } - private void ApplyLgExpertValueRange(LgDevice.InvokableAction action) + private async void ApplyLgExpertValueRange(LgDevice.InvokableAction action) { var value = ShowLgActionForm(action); @@ -991,15 +982,15 @@ Do you want to continue?" var values = value.Split(";"); - _lgService.SelectedDevice?.ExecuteAction(action, values); + await _lgService.SelectedDevice?.ExecuteActionAsync(action, values); } - private void btnLgExpertPresetAction_Click(object sender, EventArgs e) + private async void btnLgExpertPresetAction_Click(object sender, EventArgs e) { var item = sender as ToolStripItem; var preset = (LgPreset)item.Tag; - _lgService.ApplyPreset(preset).ConfigureAwait(false); + await _lgService.ApplyPreset(preset); } private void miLgEnableMotionPro_Click(object sender, EventArgs e) @@ -1142,7 +1133,7 @@ Do you want to continue?" FormUtils.ListViewItemChecked(lvLgPresets, e); } - private void miTestPowerOffOn_Click(object sender, EventArgs e) + private async void miTestPowerOffOn_Click(object sender, EventArgs e) { var text = @"The TV will now power off. Please wait for the TV to be powered off completely (relay click) and press ENTER to wake it again. @@ -1157,7 +1148,7 @@ Do you want to continue?"; if (MessageForms.QuestionYesNo(text) == DialogResult.Yes) { - Utils.WaitForTask(_lgService.PowerOff()); + await _lgService.PowerOff(); MessageForms.InfoOk("Press ENTER to wake the TV."); @@ -1289,13 +1280,34 @@ The InStart, EzAdjust and Software Update items are now visible under the Expert MaxValue = 3600, Value = device.ScreenSaverMinimalDuration }; + var turnOffField = new MessageForms.FieldDefinition + { + Label = "Turn screen off instead of power off", + FieldType = MessageForms.FieldType.CheckBox, + Value = device.TurnScreenOffOnScreenSaver + }; + var turnOnField = new MessageForms.FieldDefinition + { + Label = "Turn screen on instead of power on", + FieldType = MessageForms.FieldType.CheckBox, + Value = device.TurnScreenOnAfterScreenSaver + }; + var manualField = new MessageForms.FieldDefinition + { + Label = "Perform action even on manually executed screen saver", + FieldType = MessageForms.FieldType.CheckBox, + Value = device.HandleManualScreenSaver + }; - if (!MessageForms.ShowDialog($"Settings - {selectedItem}", new[] { durationField }).Any()) + if (!MessageForms.ShowDialog($"Settings - {selectedItem}", new[] { durationField, turnOffField, turnOnField, manualField }).Any()) { return; } device.ScreenSaverMinimalDuration = durationField.ValueAsInt; + device.TurnScreenOffOnScreenSaver = turnOffField.ValueAsBool; + device.TurnScreenOnAfterScreenSaver = turnOnField.ValueAsBool; + device.HandleManualScreenSaver = manualField.ValueAsBool; } } } diff --git a/ColorControl/Services/LG/LgService.cs b/ColorControl/Services/LG/LgService.cs index edf7706..edff430 100644 --- a/ColorControl/Services/LG/LgService.cs +++ b/ColorControl/Services/LG/LgService.cs @@ -9,7 +9,6 @@ using Newtonsoft.Json; using NWin32; using System; using System.Collections.Generic; -using System.ComponentModel; using System.Diagnostics; using System.IO; using System.Linq; @@ -21,22 +20,6 @@ namespace ColorControl.Services.LG { class LgService : ServiceBase { - internal enum PowerOnOffState - { - StartUp = 1, - Resume = 2, - ScreenSaver = 3, - ShutDown = 4, - StandBy = 5 - } - - internal enum WindowsPowerSetting - { - Off = 0, - On = 1, - Dimmed = 2 - } - internal class ProcessMonitorContext { public List Devices { get; set; } @@ -80,6 +63,7 @@ namespace ColorControl.Services.LG private readonly PowerEventDispatcher _powerEventDispatcher; private readonly SessionSwitchDispatcher _sessionSwitchDispatcher; private readonly ProcessEventDispatcher _processEventDispatcher; + private readonly ServiceManager _serviceManager; private LgDevice _selectedDevice; private string _rcButtonsFilename; private List _remoteControlButtons; @@ -91,16 +75,18 @@ namespace ColorControl.Services.LG private RestartDetector _restartDetector; private SynchronizationContext _syncContext; - public LgService(AppContextProvider appContextProvider, PowerEventDispatcher powerEventDispatcher, SessionSwitchDispatcher sessionSwitchDispatcher, ProcessEventDispatcher processEventDispatcher) : base(appContextProvider) + public LgService(AppContextProvider appContextProvider, PowerEventDispatcher powerEventDispatcher, SessionSwitchDispatcher sessionSwitchDispatcher, ProcessEventDispatcher processEventDispatcher, ServiceManager serviceManager) : base(appContextProvider) { _allowPowerOn = appContextProvider.GetAppContext().StartUpParams.RunningFromScheduledTask; _powerEventDispatcher = powerEventDispatcher; _sessionSwitchDispatcher = sessionSwitchDispatcher; _processEventDispatcher = processEventDispatcher; + _serviceManager = serviceManager; LgPreset.LgApps = _lgApps; _restartDetector = new RestartDetector(); - _syncContext = AsyncOperationManager.SynchronizationContext; + _syncContext = appContextProvider.GetAppContext().SynchronizationContext; + LgTvApiCore.SyncContext = _syncContext; LoadConfig(); LoadPresets(); @@ -364,13 +350,9 @@ namespace ColorControl.Services.LG } } - public override bool ApplyPreset(LgPreset preset) + public override async Task ApplyPreset(LgPreset preset) { - var task = ApplyPreset(preset, false); - - Utils.WaitForTask(task); - - return task.Result; + return await ApplyPreset(preset, false); } public async Task ApplyPreset(LgPreset preset, bool reconnect = false) @@ -443,13 +425,16 @@ namespace ColorControl.Services.LG state == PowerOnOffState.Resume && d.PowerOnAfterResume || state == PowerOnOffState.ScreenSaver && d.PowerOnAfterScreenSaver); - PowerOnDevices(wakeDevices, state, checkUserSession); + PowerOnDevicesTask(wakeDevices, state, checkUserSession); } public void InstallEventHandlers() { _powerEventDispatcher.RegisterEventHandler(PowerEventDispatcher.Event_Suspend, PowerModeChanged); _powerEventDispatcher.RegisterEventHandler(PowerEventDispatcher.Event_Resume, PowerModeChanged); + _powerEventDispatcher.RegisterEventHandler(PowerEventDispatcher.Event_Shutdown, PowerModeChanged); + _powerEventDispatcher.RegisterEventHandler(PowerEventDispatcher.Event_MonitorOff, PowerModeChanged); + _powerEventDispatcher.RegisterEventHandler(PowerEventDispatcher.Event_MonitorOn, PowerModeChanged); //SystemEvents.SessionEnded -= SessionEnded; //SystemEvents.SessionEnded += SessionEnded; @@ -479,20 +464,44 @@ namespace ColorControl.Services.LG } } - private void PowerModeChanged(object sender, PowerModeChangedEventArgs e) + private void PowerModeChanged(object sender, PowerStateChangedEventArgs e) { - var powerOn = e.Mode == PowerModes.Resume; + Logger.Debug($"PowerModeChanged: {e.State}"); - Logger.Debug($"PowerModeChanged: {e.Mode}"); - - if (powerOn) + switch (e.State) { - WakeAfterStartupOrResume(PowerOnOffState.Resume); - return; - } + case PowerOnOffState.Resume: + { + WakeAfterStartupOrResume(PowerOnOffState.Resume); + break; + } + case PowerOnOffState.StandBy: + { + var devices = Devices.Where(d => d.PowerOffOnStandby); + PowerOffDevices(devices, PowerOnOffState.StandBy); + break; + } + case PowerOnOffState.ShutDown: + { + var devices = Devices.Where(d => d.PowerOffOnShutdown); - var devices = Devices.Where(d => d.PowerOffOnStandby); - PowerOffDevices(devices, PowerOnOffState.StandBy); + PowerOffDevices(devices); + break; + } + + case PowerOnOffState.MonitorOff: + { + var devices = Devices.Where(d => d.PowerOffByWindows).ToList(); + PowerOffDevices(devices, PowerOnOffState.MonitorOff); + break; + } + case PowerOnOffState.MonitorOn: + { + var devices = Devices.Where(d => d.PowerOnByWindows).ToList(); + PowerOnDevicesTask(devices); + break; + } + } } private void SessionEnded(object sender, SessionEndedEventArgs e) @@ -552,14 +561,21 @@ namespace ColorControl.Services.LG return; } + var process = processes.FirstOrDefault(p => p.ProcessName.ToLowerInvariant().EndsWith(".scr")); + + if (process != null) + { + Logger.Debug($"Detected screen saver process switch from {_poweredOffByScreenSaverProcessId} to {process.Id}"); + + _poweredOffByScreenSaverProcessId = process.Id; + return; + } + Logger.Debug("Screensaver stopped, waking"); _poweredOffByScreenSaver = false; _poweredOffByScreenSaverProcessId = 0; - _syncContext.Send((x) => - { - WakeAfterStartupOrResume(PowerOnOffState.ScreenSaver); - }, null); + WakeAfterStartupOrResume(PowerOnOffState.ScreenSaver); return; } @@ -581,6 +597,7 @@ namespace ColorControl.Services.LG foreach (var device in devices) { Logger.Debug($"Process monitor: test connection with {device.Name}..."); + var test = await device.TestConnection(); Logger.Debug("Process monitor: test connection result: " + test); } @@ -650,7 +667,7 @@ namespace ColorControl.Services.LG var isHDRActive = triggerDevices.Any(d => d.IsUsingHDRPictureMode()); - var isGsyncActive = LgDevice.ExternalServiceHandler("GsyncEnabled", new[] { "" }); + var isGsyncActive = await _serviceManager.HandleExternalServiceAsync("GsyncEnabled", new[] { "" }); var triggerContext = new PresetTriggerContext { @@ -670,6 +687,8 @@ namespace ColorControl.Services.LG if (_lastTriggeredPreset != toApplyPreset) { + Logger.Debug($"Applying triggered preset: {toApplyPreset.name} because trigger conditions are met"); + await ApplyPreset(toApplyPreset); _lastTriggeredPreset = toApplyPreset; @@ -692,8 +711,8 @@ namespace ColorControl.Services.LG var parent = process.Parent(processes); - // Ignore manually started screen savers - if (parent?.ProcessName.Contains("winlogon") != true) + // Ignore manually started screen savers if no devices prefer this + if (parent?.ProcessName.Contains("winlogon") != true && !connectedDevices.Any(d => d.HandleManualScreenSaver)) { return; } @@ -705,15 +724,7 @@ namespace ColorControl.Services.LG { Logger.Debug($"Screensaver check: test connection with {device.Name}..."); - var test = false; - - _syncContext.Send((x) => - { - var task = device.TestConnection(); - test = Utils.WaitForTask(task); - }, null); - - //var test = await device.TestConnection(); + var test = await device.TestConnection(); Logger.Debug("Screensaver check: test connection result: " + test); if (!test) { @@ -734,7 +745,7 @@ namespace ColorControl.Services.LG Logger.Debug($"Screensaver check: powering off tv {device.Name} because of screensaver"); try { - _poweredOffByScreenSaver = await device.PowerOff(true).WaitAsync(TimeSpan.FromSeconds(5)); + _poweredOffByScreenSaver = await device.PerformActionOnScreenSaver().WaitAsync(TimeSpan.FromSeconds(5)); } catch (TimeoutException) { @@ -783,25 +794,6 @@ namespace ColorControl.Services.LG } } - public void PowerSettingChanged(WindowsPowerSetting setting) - { - if (Devices == null) - { - return; - } - - if (setting == WindowsPowerSetting.Off) - { - var devices = Devices.Where(d => d.PowerOffByWindows).ToList(); - PowerOffDevices(devices, PowerOnOffState.StandBy); - } - else if (setting == WindowsPowerSetting.On) - { - var devices = Devices.Where(d => d.PowerOnByWindows).ToList(); - PowerOnDevices(devices); - } - } - public void PowerOffDevices(IEnumerable devices, PowerOnOffState state = PowerOnOffState.ShutDown) { if (!devices.Any()) @@ -815,14 +807,15 @@ namespace ColorControl.Services.LG return; } - NativeMethods.SetThreadExecutionState(NativeConstants.ES_CONTINUOUS | NativeConstants.ES_SYSTEM_REQUIRED | NativeConstants.ES_AWAYMODE_REQUIRED); + var error = NativeMethods.SetThreadExecutionState(NativeConstants.ES_CONTINUOUS | NativeConstants.ES_SYSTEM_REQUIRED | NativeConstants.ES_AWAYMODE_REQUIRED); try { + Logger.Debug($"SetThreadExecutionState: {error}, Thread#: {Environment.CurrentManagedThreadId}"); if (state == PowerOnOffState.ShutDown) { var sleep = Config.ShutdownDelay; - Logger.Debug($"PowerOffDevices: Waiting for {sleep} milliseconds..."); + Logger.Debug($"PowerOffDevices: Waiting for a maximum of {sleep} milliseconds..."); while (sleep > 0 && _restartDetector?.PowerOffDetected == false) { @@ -842,7 +835,7 @@ namespace ColorControl.Services.LG var tasks = new List(); foreach (var device in devices) { - var task = device.PowerOff(true); + var task = device.PowerOff(true, false); tasks.Add(task); } @@ -856,17 +849,24 @@ namespace ColorControl.Services.LG } } - var waitTask = Task.WhenAll(tasks.ToArray()); - Utils.WaitForTask(waitTask); + // We can't use async here because we need to stay on the main thread... + var _ = Task.WhenAll(tasks.ToArray()).ConfigureAwait(true); + Logger.Debug("Done powering off tv(s)"); } finally { - NativeMethods.SetThreadExecutionState(NativeConstants.ES_CONTINUOUS); + var error2 = NativeMethods.SetThreadExecutionState(NativeConstants.ES_CONTINUOUS); + Logger.Debug($"SetThreadExecutionState (reset): {error2}, Thread#: {Environment.CurrentManagedThreadId}"); } } - public void PowerOnDevices(IEnumerable devices, PowerOnOffState state = PowerOnOffState.StartUp, bool checkUserSession = true) + public void PowerOnDevicesTask(IEnumerable devices, PowerOnOffState state = PowerOnOffState.StartUp, bool checkUserSession = true) + { + Task.Run(async () => await PowerOnDevices(devices, state, checkUserSession)); + } + + public async Task PowerOnDevices(IEnumerable devices, PowerOnOffState state = PowerOnOffState.StartUp, bool checkUserSession = true) { if (!devices.Any()) { @@ -891,17 +891,20 @@ namespace ColorControl.Services.LG continue; } - device.DisposeConnection(); + if (state == PowerOnOffState.ScreenSaver) + { + tasks.Add(device.PerformActionAfterScreenSaver(Config.PowerOnRetries)); + continue; + } var task = device.WakeAndConnectWithRetries(Config.PowerOnRetries); tasks.Add(task); } + await Task.WhenAll(tasks.ToArray()); + if (File.Exists(resumeScript)) { - var waitTask = Task.WhenAll(tasks.ToArray()); - Utils.WaitForTask(waitTask); - Utils.StartProcess(resumeScript, hidden: true); } } diff --git a/ColorControl/Services/LG/RemoteControlForm.cs b/ColorControl/Services/LG/RemoteControlForm.cs index 703efeb..5a8dc04 100644 --- a/ColorControl/Services/LG/RemoteControlForm.cs +++ b/ColorControl/Services/LG/RemoteControlForm.cs @@ -112,32 +112,32 @@ namespace ColorControl.Services.LG HandleKey(e.KeyCode); } - private void chkDirectMode_CheckedChanged(object sender, EventArgs e) + private async void chkDirectMode_CheckedChanged(object sender, EventArgs e) { if (chkDirectMode.Checked) { -// MessageForms.InfoOk( -//@"If you enable Direct Mode you will be able to control the TV directly via your keyboard and mouse. -//Note that your mouse will be captured in a box and that due to pointer accelaration the control will not be perfect. + // MessageForms.InfoOk( + //@"If you enable Direct Mode you will be able to control the TV directly via your keyboard and mouse. + //Note that your mouse will be captured in a box and that due to pointer accelaration the control will not be perfect. -//Keyboard keys: -//- arrow keys: navigate the menu -//- backspace: go back -//- escape: exit -//- S: open picture settings -//- media keys: volume up/down/mute + //Keyboard keys: + //- arrow keys: navigate the menu + //- backspace: go back + //- escape: exit + //- S: open picture settings + //- media keys: volume up/down/mute -//Mouse: -//- left button: activate/open item -//- right button: go back -//- wheel: scroll through menus (only vertically) + //Mouse: + //- left button: activate/open item + //- right button: go back + //- wheel: scroll through menus (only vertically) -//Press F1 to stop Direct Mode." -// ); + //Press F1 to stop Direct Mode." + // ); if (_mouseService == null) { - _lgService.GetMouseAsync().ContinueWith((task) => BeginInvoke(new Action>(SetMouseService), new[] { task })); + await _lgService.GetMouseAsync().ContinueWith((task) => BeginInvoke(new Action>(SetMouseService), new[] { task })); } } else diff --git a/ColorControl/Services/NVIDIA/NvPanel.cs b/ColorControl/Services/NVIDIA/NvPanel.cs index be6b262..4d7d5ed 100644 --- a/ColorControl/Services/NVIDIA/NvPanel.cs +++ b/ColorControl/Services/NVIDIA/NvPanel.cs @@ -1,6 +1,7 @@ using ColorControl.Common; using ColorControl.Forms; using ColorControl.Native; +using ColorControl.Services.Common; using nspector; using nspector.Common; using nspector.Common.Meta; @@ -28,15 +29,16 @@ namespace ColorControl.Services.NVIDIA private Config _config; private NvService _nvService; private IntPtr _mainHandle; + private readonly AppContextProvider _appContextProvider; private string _lastDisplayRefreshRates = string.Empty; private NotifyIcon _trayIcon; - public NvPanel(NvService nvService, NotifyIcon trayIcon, IntPtr handle) + public NvPanel(NvService nvService, NotifyIcon trayIcon, IntPtr handle, Common.AppContextProvider appContextProvider) { _nvService = nvService; _trayIcon = trayIcon; _mainHandle = handle; - + _appContextProvider = appContextProvider; _config = AppContext.CurrentContext.Config; InitializeComponent(); @@ -141,6 +143,7 @@ namespace ColorControl.Services.NVIDIA item.Font = new Font(item.Font, item.Font.Style | FontStyle.Bold); item.BackColor = Color.LightGray; } + //item.BackColor = _appContextProvider.GetAppContext().Config.UseDarkMode ? Color.DimGray : Color.LightGray; var values = displayInfo.Values; @@ -184,9 +187,9 @@ namespace ColorControl.Services.NVIDIA FormUtils.AddOrUpdateListItem(lvNvPresets, _nvService.GetPresets(), _config, preset); } - private void btnApply_Click(object sender, EventArgs e) + private async void btnApply_Click(object sender, EventArgs e) { - ApplySelectedNvPreset(); + await ApplySelectedNvPreset(); } private void lvNvPresets_ItemChecked(object sender, ItemCheckedEventArgs e) @@ -829,13 +832,13 @@ namespace ColorControl.Services.NVIDIA AddOrUpdateItem(); } - private void ApplySelectedNvPreset() + private async Task ApplySelectedNvPreset() { var preset = GetSelectedNvPreset(); - ApplyNvPreset(preset); + await ApplyNvPreset(preset); } - public bool ApplyNvPreset(NvPreset preset) + public async Task ApplyNvPreset(NvPreset preset) { if (preset == null || _nvService == null) { @@ -843,7 +846,7 @@ namespace ColorControl.Services.NVIDIA } try { - var result = _nvService.ApplyPreset(preset); + var result = await _nvService.ApplyPreset(preset); if (!result) { throw new Exception("Error while applying NVIDIA preset. At least one setting could not be applied. Check the log for details."); @@ -1407,7 +1410,7 @@ namespace ColorControl.Services.NVIDIA AddOrUpdateItem(); } - private void ApplyNvPresetOnStartup(int attempts = 5) + private async Task ApplyNvPresetOnStartup(int attempts = 5) { var startUpParams = AppContext.CurrentContext.StartUpParams; @@ -1427,19 +1430,14 @@ namespace ColorControl.Services.NVIDIA { if (_nvService.HasDisplaysAttached()) { - ApplyNvPreset(preset); + await ApplyNvPreset(preset); + return; } - else + attempts--; + if (attempts > 0) { - attempts--; - if (attempts > 0) - { - Task.Run(async () => - { - await Task.Delay(2000); - BeginInvoke(() => ApplyNvPresetOnStartup(attempts)); - }); - } + await Task.Delay(2000); + await ApplyNvPresetOnStartup(attempts); } } } @@ -1489,7 +1487,7 @@ namespace ColorControl.Services.NVIDIA public void AfterInitialized() { - ApplyNvPresetOnStartup(); + var _ = ApplyNvPresetOnStartup(); } internal void Save() diff --git a/ColorControl/Services/NVIDIA/NvService.cs b/ColorControl/Services/NVIDIA/NvService.cs index 6c55b9f..861d82f 100644 --- a/ColorControl/Services/NVIDIA/NvService.cs +++ b/ColorControl/Services/NVIDIA/NvService.cs @@ -19,6 +19,7 @@ using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Threading; +using System.Threading.Tasks; namespace ColorControl.Services.NVIDIA { @@ -145,7 +146,7 @@ namespace ColorControl.Services.NVIDIA LoadPresets(); } - public static bool ExecutePresetAsync(string idOrName) + public static async Task ExecutePresetAsync(string idOrName) { try { @@ -153,7 +154,7 @@ namespace ColorControl.Services.NVIDIA var nvService = new NvService(appContextProvider); - var result = nvService.ApplyPreset(idOrName); + var result = await nvService.ApplyPreset(idOrName); if (!result) { @@ -253,12 +254,12 @@ namespace ColorControl.Services.NVIDIA } } - public bool ApplyPreset(string idOrName) + public async Task ApplyPreset(string idOrName) { var preset = GetPresetByIdOrName(idOrName); if (preset != null) { - return ApplyPreset(preset); + return await ApplyPreset(preset); } else { @@ -266,7 +267,7 @@ namespace ColorControl.Services.NVIDIA } } - public override bool ApplyPreset(NvPreset preset) + public override async Task ApplyPreset(NvPreset preset) { var result = true; diff --git a/ColorControl/Svc/ColorControlBackgroundService.cs b/ColorControl/Svc/ColorControlBackgroundService.cs index b260e37..3776d41 100644 --- a/ColorControl/Svc/ColorControlBackgroundService.cs +++ b/ColorControl/Svc/ColorControlBackgroundService.cs @@ -112,7 +112,7 @@ namespace ColorControl.Svc SvcMessageType.SetLgConfig => HandleSetLgConfigMessage(message), SvcMessageType.GetLog => HandleGetLogMessage(message), SvcMessageType.ClearLog => HandleClearLogMessage(message), - SvcMessageType.ExecuteRpc => HandleExecuteRpcCommand(message), + SvcMessageType.ExecuteRpc => await HandleExecuteRpcCommand(message), SvcMessageType.ExecuteUpdate => await HandleExecuteUpdateCommandAsync(JsonConvert.DeserializeObject(json)), SvcMessageType.RestartAfterUpdate => HandleRestartAfterUpdateMessage(), SvcMessageType.ApplyNvidiaDriverSettings => HandleNvDriverSettingsMessage(JsonConvert.DeserializeObject(json)), @@ -124,13 +124,13 @@ namespace ColorControl.Svc return result; } - private SvcResultMessage HandleExecuteRpcCommand(SvcMessage message) + private async Task HandleExecuteRpcCommand(SvcMessage message) { var args = message.Data.Split(' '); var startUpParams = StartUpParams.Parse(args); - return SvcResultMessage.FromResult(Program.HandleStartupParams(startUpParams, null)); + return SvcResultMessage.FromResult(await Program.HandleStartupParams(startUpParams, null)); } private SvcResultMessage HandleSetLgConfigMessage(SvcMessage message) diff --git a/ColorControl/lgtv/LgTvConnection.cs b/ColorControl/lgtv/LgTvConnection.cs index 64d7d9c..32ad9ba 100644 --- a/ColorControl/lgtv/LgTvConnection.cs +++ b/ColorControl/lgtv/LgTvConnection.cs @@ -22,6 +22,8 @@ namespace LgTv public class LgTvApiCore : IDisposable { + public static SynchronizationContext SyncContext { get; set; } + public bool ConnectionClosed { get; private set; } private MessageWebSocket _connection; @@ -38,17 +40,22 @@ namespace LgTv { try { + //Logger.Debug($"Connecting from thread: {Environment.CurrentManagedThreadId}"); + _connection?.Dispose(); ConnectionClosed = false; _commandCount = 0; - _connection = new MessageWebSocket(); - _connection.Control.IgnorableServerCertificateErrors.Add(ChainValidationResult.Untrusted); - _connection.Control.IgnorableServerCertificateErrors.Add(ChainValidationResult.InvalidName); - _connection.Control.MessageType = SocketMessageType.Utf8; - _connection.MessageReceived += Connection_MessageReceived; - _connection.Closed += Connection_Closed; + // Not creating the web socket from main thread can cause a stackoverflow in combase32.dll + if (Environment.CurrentManagedThreadId != 1) + { + SyncContext.Send((_) => CreateWebSocket(), null); + } + else + { + CreateWebSocket(); + } try { @@ -82,6 +89,16 @@ namespace LgTv } } + private void CreateWebSocket() + { + _connection = new MessageWebSocket(); + _connection.Control.IgnorableServerCertificateErrors.Add(ChainValidationResult.Untrusted); + _connection.Control.IgnorableServerCertificateErrors.Add(ChainValidationResult.InvalidName); + _connection.Control.MessageType = SocketMessageType.Utf8; + _connection.MessageReceived += Connection_MessageReceived; + _connection.Closed += Connection_Closed; + } + public async Task SendMessageAsync(string message) { try diff --git a/ColorControl/lgtv/LgWebOsMouseService.cs b/ColorControl/lgtv/LgWebOsMouseService.cs index 8edb1dd..e4d7191 100644 --- a/ColorControl/lgtv/LgWebOsMouseService.cs +++ b/ColorControl/lgtv/LgWebOsMouseService.cs @@ -61,6 +61,7 @@ namespace LgTv public class LgWebOsMouseService : IDisposable { private readonly LgTvApiCore _connection; + public LgWebOsMouseService(LgTvApiCore connection) { _connection = connection; @@ -71,21 +72,17 @@ namespace LgTv var ctx = _connection.Connect(new Uri(uri), ignoreReceiver: true); return (await ctx); } - public void SendButton(int number) - { - _connection.SendMessageAsync($"type:button\nname:{number}\n\n").ConfigureAwait(false); - } - public void SendButton(ButtonType bt) + + public async Task SendButton(ButtonType bt) { var text = bt.ToString(); if (text[0] == '_') { text = text.Substring(1); } - _connection.SendMessageAsync($"type:button\nname:{text}\n\n").ConfigureAwait(false); + await _connection.SendMessageAsync($"type:button\nname:{text}\n\n"); } - public void Move(double dx, double dy, bool drag = false) { _connection.SendMessageAsync($"type:move\ndx:{dx}\ndy:{dy}\ndown:{(drag ? 1 : 0)}\n\n").ConfigureAwait(false); diff --git a/NvAPIWrapper/NvAPIWrapper.csproj b/NvAPIWrapper/NvAPIWrapper.csproj index d5822b3..3fd60fd 100644 --- a/NvAPIWrapper/NvAPIWrapper.csproj +++ b/NvAPIWrapper/NvAPIWrapper.csproj @@ -2,7 +2,7 @@ net7.0-windows10.0.20348.0 - 0.8.1.103 + 0.8.1.104 falahati.net NvAPIWrapper is a .Net wrapper for NVIDIA public API Soroush Falahati