Added windows startup options

UI refinements
This commit is contained in:
Darren Ohonba - Evans
2024-05-23 04:08:53 +01:00
parent 4198df7c23
commit cccb93f739
6 changed files with 469 additions and 204 deletions

View File

@@ -5,12 +5,14 @@ using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Security.AccessControl;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using AsusFanControl;
using AsusFanControlGUI.Properties;
using Microsoft.Win32;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
namespace AsusFanControlGUI
@@ -26,8 +28,8 @@ namespace AsusFanControlGUI
InitializeComponent();
AppDomain.CurrentDomain.ProcessExit += new EventHandler(OnProcessExit);
if (Debugger.IsAttached)
Settings.Default.Reset();
//if (Debugger.IsAttached)
// Settings.Default.Reset();
init();
}
@@ -38,14 +40,18 @@ namespace AsusFanControlGUI
{
toolStripMenuItemTurnOffControlOnExit.Checked = Properties.Settings.Default.turnOffControlOnExit;
toolStripMenuItemForbidUnsafeSettings.Checked = Properties.Settings.Default.forbidUnsafeSettings;
startMinimisedToolStripMenuItem.Checked = Properties.Settings.Default.startMinimised;
startWithWindowsToolStripMenuItem.Checked = Properties.Settings.Default.startWithWindows;
trackBarFanSpeed.Value = Properties.Settings.Default.fanSpeed;
radioButton1.Checked = Properties.Settings.Default.fanControlState == "Off";
fanControl.Checked = Properties.Settings.Default.fanControlState == "Manual";
fanCurve.Checked = Properties.Settings.Default.fanControlState == "Curve";
allowFanCurveSettingViaTextToolStripMenuItem.Checked = Properties.Settings.Default.allowFanCurveSettingViaText;
// Manually trigger events
radioButton1_CheckedChanged(radioButton1, EventArgs.Empty);
fanCurve_CheckedChanged(fanCurve, EventArgs.Empty);
fanControl_CheckedChanged(fanControl, EventArgs.Empty);
allowFanCurveSettingViaTextToolStripMenuItem_Click(allowFanCurveSettingViaTextToolStripMenuItem, EventArgs.Empty);
Properties.Settings.Default.PropertyChanged += (sender, e) =>
{
@@ -57,8 +63,6 @@ namespace AsusFanControlGUI
SetFanCurvePoints(null);
//SetFanCurvePoints("20,1;60,1;61,20;70,20;71,30;80,55");
Timer_Tick();
}
else
{
@@ -70,38 +74,51 @@ namespace AsusFanControlGUI
private async void Timer_Tick()
{
if (autoRefresh.Checked && WindowState != FormWindowState.Minimized)
if (WindowState == FormWindowState.Minimized)
{
Console.WriteLine($"Refreshing {rnd.Next(100)}");
// Update fan speeds and CPU temperature on a separate task
await Task.Run(() =>
{
// Get fan speeds
string fanSpeeds = string.Join(" ", asusControl.GetFanSpeeds());
// Get CPU temperature
string cpuTemp = $"{asusControl.Thermal_Read_Cpu_Temperature()}";
// Update UI on the main thread
BeginInvoke(new Action(() =>
{
labelRPM.Text = fanSpeeds;
labelCPUTemp.Text = cpuTemp;
}));
});
await Task.Delay(1000);
Timer_Tick();
return;
}
else
{
await Task.Delay(1000).ContinueWith(t => { Timer_Tick(); });
}
Console.WriteLine($"Refreshing {rnd.Next(100)}");
// Update fan speeds and CPU temperature.
// Run both tasks concurrently
Task<string> fanSpeedsTask = Task.Run(() => string.Join(" ", asusControl.GetFanSpeeds()));
Task<string> cpuTempTask = Task.Run(() => $"{asusControl.Thermal_Read_Cpu_Temperature()}");
// Wait for both tasks to complete
await Task.WhenAll(fanSpeedsTask, cpuTempTask);
// Get the results from the completed tasks
labelRPM.Text = fanSpeedsTask.Result;
labelCPUTemp.Text = cpuTempTask.Result;
await Task.Delay(250);
Timer_Tick();
}
private void AddToStartup()
{
string appName = Assembly.GetExecutingAssembly().GetName().Name;
string appPath = Assembly.GetExecutingAssembly().Location;
RegistryKey registryKey = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
registryKey.SetValue(appName, appPath);
}
private void RemoveFromStartup()
{
string appName = Assembly.GetExecutingAssembly().GetName().Name;
RegistryKey registryKey = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
registryKey.DeleteValue(appName, false);
}
private void OnProcessExit(object sender, EventArgs e)
{
if (Properties.Settings.Default.turnOffControlOnExit)
asusControl.SetFanSpeeds(0);
setFanSpeed(0, null);
}
private void toolStripMenuItemTurnOffControlOnExit_CheckedChanged(object sender, EventArgs e)
@@ -127,7 +144,8 @@ namespace AsusFanControlGUI
{
Properties.Settings.Default.fanControlState = "Off";
Properties.Settings.Default.Save();
asusControl.SetFanSpeeds(0);
setFanSpeed(0, null);
}
}
@@ -137,33 +155,42 @@ namespace AsusFanControlGUI
{
Properties.Settings.Default.fanControlState = "Manual";
Properties.Settings.Default.Save();
trackBarFanSpeed_MouseCaptureChanged(sender, e);
trackBarFanSpeed.Enabled = true;
trackBarSetFanSpeed();
}
else
{
trackBarFanSpeed.Enabled=false;
}
}
private void setFanSpeed(int value, bool isTurnedOn)
bool turnedoff = false;
private async void setFanSpeed(int value, bool? isTurnedOn)
{
Properties.Settings.Default.fanSpeed = value;
Properties.Settings.Default.Save();
if (!isTurnedOn)
value = 0;
if (value == 0)
BeginInvoke(new Action(() => labelValue.Text = "turned off"));
else
BeginInvoke(new Action(() => labelValue.Text = value.ToString() + "%"));
if (fanSpeed == value)
return;
if (turnedoff && value == 0)
return;
fanSpeed = value;
asusControl.SetFanSpeeds(value);
await Task.Run(() => asusControl.SetFanSpeeds(value));
if (value == 0)
{
labelValue.Text = "turned off";
turnedoff = true;
}
else
{
labelValue.Text = value.ToString() + "%";
turnedoff = false;
}
}
private async void trackBarFanSpeed_MouseCaptureChanged(object sender, EventArgs e)
private void trackBarSetFanSpeed()
{
if (Properties.Settings.Default.forbidUnsafeSettings)
{
@@ -173,12 +200,13 @@ namespace AsusFanControlGUI
trackBarFanSpeed.Value = 99;
}
Properties.Settings.Default.fanSpeed = trackBarFanSpeed.Value;
Properties.Settings.Default.Save();
Decimal trackBarFanSpeedValue = trackBarFanSpeed.Value;
label5.Text = trackBarFanSpeedValue.ToString() + "% Fan";
await Task.Run(() =>
setFanSpeed((int)trackBarFanSpeedValue, fanControl.Checked)
);
setFanSpeed((int)trackBarFanSpeedValue, fanControl.Checked);
}
private void trackBarFanSpeed_KeyUp(object sender, KeyEventArgs e)
@@ -186,34 +214,33 @@ namespace AsusFanControlGUI
if (e.KeyCode != Keys.Left && e.KeyCode != Keys.Right)
return;
trackBarFanSpeed_MouseCaptureChanged(sender, e);
trackBarSetFanSpeed();
}
private void button1_Click(object sender, EventArgs e)
private async void button1_Click(object sender, EventArgs e)
{
labelRPM.Text = string.Join(" ", asusControl.GetFanSpeeds());
List<int> fanSpeed = await Task.Run(() => asusControl.GetFanSpeeds());
labelRPM.Text = string.Join(" ", fanSpeed);
}
private void button2_Click(object sender, EventArgs e)
private async void button2_Click(object sender, EventArgs e)
{
labelCPUTemp.Text = $"{asusControl.Thermal_Read_Cpu_Temperature()}";
ulong fanSpeed = await Task.Run(() => asusControl.Thermal_Read_Cpu_Temperature());
labelCPUTemp.Text = $"{fanSpeed}";
}
// My Code:
private Point maxPoint;
private Point minPoint;
private Dictionary<int, Point> fanCurvePoints = new Dictionary<int, Point>()
{
{ 1, new Point(20, 1) },
{ 4, new Point(60, 1) },
{ 5, new Point(61, 20) },
{ 7, new Point(70, 20) },
{ 8, new Point(71, 30) },
{ 9, new Point(80, 55) },
};
{
{ 1, new Point(20, 1) },
{ 4, new Point(60, 1) },
{ 5, new Point(61, 20) },
{ 7, new Point(70, 20) },
{ 8, new Point(71, 30) },
{ 9, new Point(80, 55) },
};
private Timer fanCurveTimer; // Declare the timer as a class-level variable
// Set up the graph dimensions
@@ -286,7 +313,7 @@ namespace AsusFanControlGUI
(int temperature, int fanSpeed) = mousePosition(e.Location);
if (fanCurvePoints.Count >= 15)
if (fanCurvePoints.Count >= 20)
{
MessageBox.Show("Maximum number of points reached.");
return;
@@ -376,10 +403,24 @@ namespace AsusFanControlGUI
private void pictureBoxFanCurve_MouseMove(object sender, MouseEventArgs e)
{
byte minimumTemperature = 20;
byte maximumTemperature = 105;
byte minFanSpeed = 1;
byte maxFanSpeed = 100;
if (selectedPointId != 0)
{
// Get mouse location on grid
(int temperature, int fanSpeed) = mousePosition(e.Location);
if (temperature < minimumTemperature || temperature > maximumTemperature)
{
temperature = Math.Max(minimumTemperature, Math.Min(temperature, maximumTemperature));
}
if (fanSpeed < minFanSpeed || fanSpeed > maxFanSpeed)
{
fanSpeed = Math.Max(minFanSpeed, Math.Min(fanSpeed, maxFanSpeed));
}
//Update location of point
fanCurvePoints[selectedPointId] = new Point(temperature, fanSpeed);
@@ -408,75 +449,75 @@ namespace AsusFanControlGUI
return Math.Sqrt(dx * dx + dy * dy);
}
bool isControlYeilded = false;
private void fanCurve_CheckedChanged(object sender, EventArgs e)
{
Properties.Settings.Default.fanControlState = "Curve";
Properties.Settings.Default.Save();
if (fanCurve.Checked)
Console.WriteLine(fanCurve.Checked);
runFanCurve();
}
private async void runFanCurve()
{
if (!fanCurve.Checked)
{
// Read the current temperature
ulong currentTemp = asusControl.Thermal_Read_Cpu_Temperature(); // Implement the ReadTemperature method to get the current temperature
label3.Text = $"";
return;
}
Console.WriteLine("Fan Curve, " + (int)numericUpDown2.Value);
// Find the fan curve points that bracket the current temperature
KeyValuePair<int, Point> lowerPoint = fanCurvePoints.OrderByDescending(p => p.Value.X).FirstOrDefault(p => (ulong)p.Value.X <= currentTemp);
KeyValuePair<int, Point> upperPoint = fanCurvePoints.OrderBy(p => p.Value.X).FirstOrDefault(p => (ulong)p.Value.X >= currentTemp);
// Read the current temperature
ulong currentTemp = await Task.Run(() => asusControl.Thermal_Read_Cpu_Temperature()); // Implement the ReadTemperature method to get the current temperature
Console.WriteLine("Temp, " + currentTemp);
// Find the fan curve points that bracket the current temperature
KeyValuePair<int, Point> lowerPoint = fanCurvePoints.OrderByDescending(p => p.Value.X).FirstOrDefault(p => (ulong)p.Value.X <= currentTemp);
KeyValuePair<int, Point> upperPoint = fanCurvePoints.OrderBy(p => p.Value.X).FirstOrDefault(p => (ulong)p.Value.X >= currentTemp);
// Update UI on the main thread
label3.Text = $"Low: {lowerPoint.Value.X} High: {upperPoint.Value.X}";
// Check if the current temperature is within the range of the fan curve points
if (lowerPoint.Key == 0 || upperPoint.Key == 0)
{
// Temperature is outside the range, yield control to the system.
label3.Text = "Control yeilded to system when outside range.";
Console.WriteLine("Temperature is outside the range, yield control to the system.");
setFanSpeed(0, null);
}
else if (lowerPoint.Value.X == upperPoint.Value.X)
{
setFanSpeed(lowerPoint.Value.Y, true); // Implement the SetFanSpeed method to control the fan speed
Console.WriteLine($"Set fan speed to {lowerPoint.Value.Y}% {rnd.Next(1000)}, last fan speed = {lastFanSpeed}");
lastFanSpeed = lowerPoint.Value.Y;
}
else
{
// Calculate the fan speed based on linear interpolation between the bracket points
int fanSpeed;
// Check if the current temperature is within the range of the fan curve points
if ((ulong)lowerPoint.Key == 0 || (ulong)upperPoint.Key == 0)
double ratio = (currentTemp - (ulong)lowerPoint.Value.X) / (double)(upperPoint.Value.X - lowerPoint.Value.X);
fanSpeed = (int)(lowerPoint.Value.Y + (upperPoint.Value.Y - lowerPoint.Value.Y) * ratio);
// Apply hysteresis to prevent rapid fan speed changes
int hysteresis = (int)numericUpDown1.Value; // Adjust the hysteresis value as needed
if (fanSpeed > lastFanSpeed + hysteresis || fanSpeed < lastFanSpeed - hysteresis || fanSpeed < 10)
{
// Temperature is outside the range, yield control to the system
if (!isControlYeilded)
{
asusControl.SetFanSpeeds(0);
isControlYeilded = true;
}
// Update the fan speed
fanSpeed = Math.Max(1, Math.Min(100, fanSpeed));
setFanSpeed(fanSpeed, true); // Implement the SetFanSpeed method to control the fan speed
Console.WriteLine($"Set fan speed to {fanSpeed}% {rnd.Next(1000)}, last fan speed = {lastFanSpeed}");
lastFanSpeed = fanSpeed;
}
else if (lowerPoint.Value.X == upperPoint.Value.X)
{
setFanSpeed(lowerPoint.Value.Y, true); // Implement the SetFanSpeed method to control the fan speed
Console.WriteLine($"Set fan speed to {lowerPoint.Value.Y}% {rnd.Next(1000)}, last fan speed = {lastFanSpeed}");
// Update UI on the main thread
BeginInvoke(new Action(() =>
{
label3.Text = $"Low: {lowerPoint.Value.X} High: {upperPoint.Value.X}";
}));
lastFanSpeed = lowerPoint.Value.Y;
}
else
{
isControlYeilded = false;
double ratio = (currentTemp - (ulong)lowerPoint.Value.X) / (double)(upperPoint.Value.X - lowerPoint.Value.X);
fanSpeed = (int)(lowerPoint.Value.Y + (upperPoint.Value.Y - lowerPoint.Value.Y) * ratio);
};
await Task.Delay((int)numericUpDown2.Value);
runFanCurve();
// Apply hysteresis to prevent rapid fan speed changes
int hysteresis = (int)numericUpDown1.Value; // Adjust the hysteresis value as needed
if (fanSpeed > lastFanSpeed + hysteresis || fanSpeed < lastFanSpeed - hysteresis || fanSpeed < 10)
{
// Update the fan speed
fanSpeed = Math.Max(1, Math.Min(100, fanSpeed));
setFanSpeed(fanSpeed, true); // Implement the SetFanSpeed method to control the fan speed
Console.WriteLine($"Set fan speed to {fanSpeed}% {rnd.Next(1000)}, last fan speed = {lastFanSpeed}");
// Update UI on the main thread
BeginInvoke(new Action(() =>
{
label3.Text = $"Low: {lowerPoint.Value.X} High: {upperPoint.Value.X}";
}));
lastFanSpeed = fanSpeed;
}
};
Task.Delay((int)numericUpDown2.Value).ContinueWith(t => { fanCurve_CheckedChanged(null, null); });
}
}
// Keep track of the last fan speed to apply hysteresis
@@ -488,11 +529,16 @@ namespace AsusFanControlGUI
{
if (WindowState == FormWindowState.Minimized)
{
Hide();
notifyIcon1.Visible = true;
MinimizeToTray();
}
}
public void MinimizeToTray()
{
this.Hide();
notifyIcon1.Visible = true;
}
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
Show();
@@ -527,32 +573,33 @@ namespace AsusFanControlGUI
private void SetFanCurvePoints(String? fanCurveString)
{
int count = 0;
int count = 1;
string fanCurvePointsString = fanCurveString ?? Properties.Settings.Default.FanCurvePoints;
if (!string.IsNullOrEmpty(fanCurvePointsString))
Console.WriteLine(fanCurvePointsString);
if (string.IsNullOrEmpty(fanCurvePointsString))
{
return;
}
// Parse the string
try
{
Console.WriteLine(fanCurvePointsString);
// Parse the string
try
fanCurvePoints = fanCurvePointsString.Split('-')
.Select(x =>
{
fanCurvePoints = fanCurvePointsString.Split('-')
.Select(x =>
{
string[] parts = x.Split(',');
return new KeyValuePair<int, Point>(count++, new Point(int.Parse(parts[0]), int.Parse(parts[1])));
})
.ToDictionary(x => x.Key, x => x.Value);
string[] parts = x.Split(',');
return new KeyValuePair<int, Point>(count++, new Point(int.Parse(parts[0]), int.Parse(parts[1])));
})
.ToDictionary(x => x.Key, x => x.Value);
//Save
textBox1.Text = fanCurvePointsString;
SaveFanCurvePoints();
}
catch
{
MessageBox.Show("Invalid string.");
}
//Save
textBox1.Text = fanCurvePointsString;
SaveFanCurvePoints();
}
catch (Exception ex)
{
throw;
}
pictureBoxFanCurve.Invalidate();
@@ -566,13 +613,113 @@ namespace AsusFanControlGUI
private void button3_Click(object sender, EventArgs e)
{
SetFanCurvePoints(textBox1.Text);
try
{
SetFanCurvePoints(textBox1.Text);
MessageBox.Show("Save successful.");
}
catch (Exception ex)
{
MessageBox.Show("An error occurred: " + ex.Message);
}
}
private void trackBarFanSpeed_MouseUp(object sender, MouseEventArgs e)
{
trackBarFanSpeed_MouseCaptureChanged(sender, e);
trackBarSetFanSpeed();
}
}
private void label1_Click(object sender, EventArgs e)
{
}
private void resetToDefaultsToolStripMenuItem_Click(object sender, EventArgs e)
{
Properties.Settings.Default.Reset();
Application.Restart();
Environment.Exit(0);
}
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar != (char)Keys.Enter)
{
return;
}
try
{
SetFanCurvePoints(textBox1.Text);
MessageBox.Show("Save successful.");
}
catch (Exception ex)
{
MessageBox.Show("An error occurred: " + ex.Message);
}
}
private void allowFanCurveSettingViaTextToolStripMenuItem_Click(object sender, EventArgs e)
{
if (allowFanCurveSettingViaTextToolStripMenuItem.Checked)
{
Properties.Settings.Default.allowFanCurveSettingViaText = true;
Properties.Settings.Default.Save();
button3.Enabled = true; textBox1.ReadOnly = false; button4.Enabled = true;
}
else
{
Properties.Settings.Default.allowFanCurveSettingViaText = false;
Properties.Settings.Default.Save();
button3.Enabled = false; textBox1.ReadOnly = true; button4.Enabled = false;
}
}
private void textBox1_MouseHover(object sender, EventArgs e)
{
toolTip1.Show(textBox1.Text, textBox1);
}
private void startWithWindowsToolStripMenuItem1_Click_1(object sender, EventArgs e)
{
if (startWithWindowsToolStripMenuItem.Checked)
{
Properties.Settings.Default.startWithWindows = true;
Properties.Settings.Default.Save();
AddToStartup();
}
else
{
Properties.Settings.Default.startWithWindows = false;
Properties.Settings.Default.Save();
RemoveFromStartup();
}
}
private void startMinimisedToolStripMenuItem_Click(object sender, EventArgs e)
{
if (startMinimisedToolStripMenuItem.Checked)
{
Properties.Settings.Default.startMinimised = true;
Properties.Settings.Default.Save();
}
else
{
Properties.Settings.Default.startMinimised = false;
Properties.Settings.Default.Save();
}
}
private void Form1_Shown(object sender, EventArgs e)
{
bool startMinimized = Properties.Settings.Default.startMinimised;
if (startMinimized)
{
MinimizeToTray();
}
}
//notifyIcon1.BalloonTipText = string.Join(" ", asusControl.GetFanSpeeds()) + $" Temp: {asusControl.Thermal_Read_Cpu_Temperature()}"; }
}
}