Skip to content

Commit

Permalink
Add autorun
Browse files Browse the repository at this point in the history
  • Loading branch information
andersforsgren committed Jan 10, 2021
1 parent cb39f9b commit 85a3cfd
Show file tree
Hide file tree
Showing 3 changed files with 91 additions and 7 deletions.
25 changes: 19 additions & 6 deletions Source/Knatter.Application/MuteForm.Designer.cs

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

11 changes: 10 additions & 1 deletion Source/Knatter.Application/MuteForm.cs
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,10 @@ public MuteForm()
Text = ProgramInfo.NameAndVersion;
Icon = Resources.Unmute;
ShowIcon = true;

SetAutorunState();

muter.DeviceListChanged += (s, e) => InvokeIfRequired(() => LoadDevices(muter.Device.Id));
autoStartCheckbox.CheckedChanged += (s, e) => { AutoRun.Enable(autoStartCheckbox.Checked, $"\"{Assembly.GetEntryAssembly().Location}\" /background"); SetAutorunState(); };
pausedCheckbox.CheckedChanged += (s, e) => muter.Pause(pausedCheckbox.Checked);
deviceCombo.SelectedIndexChanged += (s, e) => muter.SetDevice(((ComboBoxItem)deviceCombo.SelectedItem).Value as CoreAudioDevice);
unmuteTimeTrackbar.ValueChanged += (s, e) =>
Expand All @@ -56,6 +58,13 @@ public MuteForm()
LoadDevices(lastUsedUnmuteDeviceId);
}

private void SetAutorunState()
{
bool? autoRun = AutoRun.IsEnabled();
autoStartCheckbox.Enabled = autoRun.HasValue;
autoStartCheckbox.Checked = autoRun ?? false;
}

private void LoadDevices(Guid? idOfPrefderredDevice)
{
deviceCombo.Items.Clear();
Expand Down
62 changes: 62 additions & 0 deletions Source/Knatter.Core/AutoRun.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
using Microsoft.Win32;
using System;
using System.Diagnostics;
using System.Reflection;

namespace Knatter.Core
{
public static class AutoRun
{
private const string RegKey = @"Software\Microsoft\Windows\CurrentVersion\Run";
private static readonly string RegValue = ProgramInfo.Name;

public static bool? IsEnabled()
{
try
{
return Registry.GetValue($"HKEY_CURRENT_USER\\{RegKey}", RegValue, null) is string;
}
catch (Exception ex)
{
Debug.WriteLine("Error reading autorun key: "+ex);
return null;
}
}

public static bool? Enable(bool enabled, string commandLine)
{
try
{
bool? isEnabled = IsEnabled();
if (!isEnabled.HasValue)
return isEnabled;

if (isEnabled.Value == enabled)
return isEnabled;

using (RegistryKey key = Registry.CurrentUser.OpenSubKey(RegKey, true))
{
if (enabled)
{
Debug.WriteLine($"Adding regkey for autostart: {RegValue}='{commandLine}'");
key.SetValue(RegValue, commandLine);
}
else
{
Debug.WriteLine($"Removing regkey for autostart: {RegValue}");
key.DeleteValue(RegValue);
}
key.Dispose();
key.Flush();
}
return enabled;
}
catch (Exception ex)
{
Debug.WriteLine("Error writing autorun key: " + ex);
return null;
}
}

}
}

0 comments on commit 85a3cfd

Please sign in to comment.