Check for optimization service before setting backlight

This commit is contained in:
Serge
2023-06-04 12:18:51 +02:00
parent d5b098335b
commit 17083eef21
10 changed files with 117 additions and 107 deletions

View File

@@ -135,19 +135,7 @@ public class AmdGpuControl : IGpuControl
} }
} }
foreach (string kill in appNames) foreach (string kill in appNames) ProcessHelper.KillByName(kill);
foreach (var process in Process.GetProcessesByName(kill))
{
try
{
process.Kill();
Logger.WriteLine($"Stopped: {process.ProcessName}");
}
catch (Exception ex)
{
Logger.WriteLine($"Failed to stop: {process.ProcessName} {ex.Message}");
}
}
} catch (Exception ex) } catch (Exception ex)

View File

@@ -6,7 +6,6 @@ public interface IGpuControl : IDisposable {
public string FullName { get; } public string FullName { get; }
int? GetCurrentTemperature(); int? GetCurrentTemperature();
int? GetGpuUse(); int? GetGpuUse();
void KillGPUApps(); void KillGPUApps();
} }

View File

@@ -55,26 +55,13 @@ public class NvidiaGpuControl : IGpuControl
try try
{ {
Process[] processes = internalGpu.GetActiveApplications(); Process[] processes = internalGpu.GetActiveApplications();
foreach (Process process in processes) foreach (Process process in processes) ProcessHelper.KillByProcess(process);
{
try
{
process?.Kill();
Logger.WriteLine("Stopped: " + process.ProcessName);
}
catch (Exception ex)
{
Logger.WriteLine(ex.Message);
}
}
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.WriteLine(ex.Message); Logger.WriteLine(ex.Message);
} }
//NVIDIA.RestartDisplayDriver(); //NVIDIA.RestartDisplayDriver();
} }

View File

@@ -187,7 +187,7 @@ public static class HardwareControl
public static void KillGPUApps() public static void KillGPUApps()
{ {
List<string> tokill = new() { "EADesktop", "RadeonSoftware", "epicgameslauncher" }; List<string> tokill = new() { "EADesktop", "RadeonSoftware", "epicgameslauncher", "ASUSSmartDisplayControl" };
if (AppConfig.isConfig("kill_gpu_apps")) if (AppConfig.isConfig("kill_gpu_apps"))
{ {
@@ -196,19 +196,7 @@ public static class HardwareControl
tokill.Add("nvcplui"); tokill.Add("nvcplui");
} }
foreach (string kill in tokill) foreach (string kill in tokill) ProcessHelper.KillByName(kill);
foreach (var process in Process.GetProcessesByName(kill))
{
try
{
process.Kill();
Logger.WriteLine($"Stopped: {process.ProcessName}");
}
catch (Exception ex)
{
Logger.WriteLine($"Failed to stop: {process.ProcessName} {ex.Message}");
}
}
if (AppConfig.isConfig("kill_gpu_apps") && GpuControl is not null) if (AppConfig.isConfig("kill_gpu_apps") && GpuControl is not null)
{ {

View File

@@ -429,7 +429,8 @@ namespace GHelper
public static void SetBacklightAuto(bool init = false) public static void SetBacklightAuto(bool init = false)
{ {
if (init) AsusUSB.Init(); if (init) AsusUSB.Init();
AsusUSB.ApplyBrightness(GetBacklight(), "Auto");
if (!OptimizationService.IsRunning()) AsusUSB.ApplyBrightness(GetBacklight(), "Auto");
} }
public static void SetBacklight(int delta) public static void SetBacklight(int delta)

View File

@@ -30,7 +30,7 @@ public static class Logger
try try
{ {
var file = File.ReadAllLines(logFile); var file = File.ReadAllLines(logFile);
int skip = Math.Max(0, file.Count() - 500); int skip = Math.Max(0, file.Count() - 1000);
File.WriteAllLines(logFile, file.Skip(skip).ToArray()); File.WriteAllLines(logFile, file.Skip(skip).ToArray());
} }
catch { } catch { }

97
app/ProcessHelper.cs Normal file
View File

@@ -0,0 +1,97 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Security.Principal;
using System.Text;
using System.Threading.Tasks;
namespace GHelper
{
public static class ProcessHelper
{
private static long lastAdmin;
public static void CheckAlreadyRunning()
{
Process currentProcess = Process.GetCurrentProcess();
Process[] processes = Process.GetProcessesByName(currentProcess.ProcessName);
if (processes.Length > 1)
{
foreach (Process process in processes)
if (process.Id != currentProcess.Id)
try
{
process.Kill();
}
catch (Exception ex)
{
Logger.WriteLine(ex.ToString());
MessageBox.Show(Properties.Strings.AppAlreadyRunningText, Properties.Strings.AppAlreadyRunning, MessageBoxButtons.OK);
Application.Exit();
return;
}
}
}
public static bool IsUserAdministrator()
{
WindowsIdentity identity = WindowsIdentity.GetCurrent();
WindowsPrincipal principal = new WindowsPrincipal(identity);
return principal.IsInRole(WindowsBuiltInRole.Administrator);
}
public static void RunAsAdmin(string? param = null)
{
if (Math.Abs(DateTimeOffset.Now.ToUnixTimeMilliseconds() - lastAdmin) < 2000) return;
lastAdmin = DateTimeOffset.Now.ToUnixTimeMilliseconds();
// Check if the current user is an administrator
if (!IsUserAdministrator())
{
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.UseShellExecute = true;
startInfo.WorkingDirectory = Environment.CurrentDirectory;
startInfo.FileName = Application.ExecutablePath;
startInfo.Arguments = param;
startInfo.Verb = "runas";
Process.Start(startInfo);
Application.Exit();
}
}
public static void KillByName(string name)
{
foreach (var process in Process.GetProcessesByName(name))
{
try
{
process.Kill();
Logger.WriteLine($"Stopped: {process.ProcessName}");
}
catch (Exception ex)
{
Logger.WriteLine($"Failed to stop: {process.ProcessName} {ex.Message}");
}
}
}
public static void KillByProcess(Process process)
{
try
{
process.Kill();
Logger.WriteLine($"Stopped: {process.ProcessName}");
}
catch (Exception ex)
{
Logger.WriteLine($"Failed to stop: {process.ProcessName} {ex.Message}");
}
}
}
}

View File

@@ -25,7 +25,6 @@ namespace GHelper
private static long lastAuto; private static long lastAuto;
private static long lastTheme; private static long lastTheme;
private static long lastAdmin;
public static InputDispatcher inputDispatcher; public static InputDispatcher inputDispatcher;
@@ -48,7 +47,7 @@ namespace GHelper
Debug.WriteLine(CultureInfo.CurrentUICulture); Debug.WriteLine(CultureInfo.CurrentUICulture);
//Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture("fr"); //Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture("fr");
CheckProcesses(); ProcessHelper.CheckAlreadyRunning();
try try
{ {
@@ -67,7 +66,7 @@ namespace GHelper
} }
Logger.WriteLine("------------"); Logger.WriteLine("------------");
Logger.WriteLine("App launched: " + AppConfig.GetModel() + " :" + Assembly.GetExecutingAssembly().GetName().Version.ToString() + CultureInfo.CurrentUICulture + (IsUserAdministrator() ? "." : "")); Logger.WriteLine("App launched: " + AppConfig.GetModel() + " :" + Assembly.GetExecutingAssembly().GetName().Version.ToString() + CultureInfo.CurrentUICulture + (ProcessHelper.IsUserAdministrator() ? "." : ""));
Application.EnableVisualStyles(); Application.EnableVisualStyles();
@@ -211,55 +210,6 @@ namespace GHelper
} }
static void CheckProcesses()
{
Process currentProcess = Process.GetCurrentProcess();
Process[] processes = Process.GetProcessesByName(currentProcess.ProcessName);
if (processes.Length > 1)
{
foreach (Process process in processes)
if (process.Id != currentProcess.Id)
try
{
process.Kill();
}
catch (Exception ex)
{
Logger.WriteLine(ex.ToString());
MessageBox.Show(Properties.Strings.AppAlreadyRunningText, Properties.Strings.AppAlreadyRunning, MessageBoxButtons.OK);
Application.Exit();
return;
}
}
}
public static bool IsUserAdministrator()
{
WindowsIdentity identity = WindowsIdentity.GetCurrent();
WindowsPrincipal principal = new WindowsPrincipal(identity);
return principal.IsInRole(WindowsBuiltInRole.Administrator);
}
public static void RunAsAdmin(string? param = null)
{
if (Math.Abs(DateTimeOffset.Now.ToUnixTimeMilliseconds() - lastAdmin) < 2000) return;
lastAdmin = DateTimeOffset.Now.ToUnixTimeMilliseconds();
// Check if the current user is an administrator
if (!IsUserAdministrator())
{
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.UseShellExecute = true;
startInfo.WorkingDirectory = Environment.CurrentDirectory;
startInfo.FileName = Application.ExecutablePath;
startInfo.Arguments = param;
startInfo.Verb = "runas";
Process.Start(startInfo);
Application.Exit();
}
}
} }
} }

View File

@@ -168,7 +168,7 @@ namespace GHelper
int trim = model.LastIndexOf("_"); int trim = model.LastIndexOf("_");
if (trim > 0) model = model.Substring(0, trim); if (trim > 0) model = model.Substring(0, trim);
labelModel.Text = model + (Program.IsUserAdministrator() ? "." : ""); labelModel.Text = model + (ProcessHelper.IsUserAdministrator() ? "." : "");
TopMost = AppConfig.getConfig("topmost") == 1; TopMost = AppConfig.getConfig("topmost") == 1;
@@ -1075,7 +1075,7 @@ namespace GHelper
} }
int setStatus = nvControl.SetClocks(gpu_core, gpu_memory); int setStatus = nvControl.SetClocks(gpu_core, gpu_memory);
if (launchAsAdmin && setStatus == -1) Program.RunAsAdmin("gpu"); if (launchAsAdmin && setStatus == -1) ProcessHelper.RunAsAdmin("gpu");
} }
catch (Exception ex) catch (Exception ex)
@@ -1502,9 +1502,9 @@ namespace GHelper
if (dialogResult == DialogResult.No) return; if (dialogResult == DialogResult.No) return;
} }
Program.RunAsAdmin("gpurestart"); ProcessHelper.RunAsAdmin("gpurestart");
if (!Program.IsUserAdministrator()) return; if (!ProcessHelper.IsUserAdministrator()) return;
Logger.WriteLine("Trying to restart dGPU"); Logger.WriteLine("Trying to restart dGPU");

View File

@@ -16,7 +16,7 @@ public class Startup
public static void ReScheduleAdmin() public static void ReScheduleAdmin()
{ {
if (Program.IsUserAdministrator() && IsScheduled()) if (ProcessHelper.IsUserAdministrator() && IsScheduled())
{ {
UnSchedule(); UnSchedule();
Schedule(); Schedule();
@@ -38,7 +38,7 @@ public class Startup
td.Triggers.Add(new LogonTrigger { UserId = userId }); td.Triggers.Add(new LogonTrigger { UserId = userId });
td.Actions.Add(strExeFilePath); td.Actions.Add(strExeFilePath);
if (Program.IsUserAdministrator()) if (ProcessHelper.IsUserAdministrator())
td.Principal.RunLevel = TaskRunLevel.Highest; td.Principal.RunLevel = TaskRunLevel.Highest;
td.Settings.StopIfGoingOnBatteries = false; td.Settings.StopIfGoingOnBatteries = false;
@@ -54,10 +54,10 @@ public class Startup
} }
catch (Exception e) catch (Exception e)
{ {
if (Program.IsUserAdministrator()) if (ProcessHelper.IsUserAdministrator())
MessageBox.Show("Can't create a start up task. Try running Task Scheduler by hand and manually deleting GHelper task if it exists there.", "Scheduler Error", MessageBoxButtons.OK); MessageBox.Show("Can't create a start up task. Try running Task Scheduler by hand and manually deleting GHelper task if it exists there.", "Scheduler Error", MessageBoxButtons.OK);
else else
Program.RunAsAdmin(); ProcessHelper.RunAsAdmin();
} }
} }
@@ -73,10 +73,10 @@ public class Startup
} }
catch (Exception e) catch (Exception e)
{ {
if (Program.IsUserAdministrator()) if (ProcessHelper.IsUserAdministrator())
MessageBox.Show("Can't remove task. Try running Task Scheduler by hand and manually deleting GHelper task if it exists there.", "Scheduler Error", MessageBoxButtons.OK); MessageBox.Show("Can't remove task. Try running Task Scheduler by hand and manually deleting GHelper task if it exists there.", "Scheduler Error", MessageBoxButtons.OK);
else else
Program.RunAsAdmin(); ProcessHelper.RunAsAdmin();
} }
} }
} }