Skip to content

Commit

Permalink
Fix Run-At-Startup setting
Browse files Browse the repository at this point in the history
Use TaskScheduler instead of registering an exe path to Windows registry to run app as administrator
  • Loading branch information
ryochack committed Mar 30, 2024
1 parent 692b367 commit acda121
Show file tree
Hide file tree
Showing 6 changed files with 67 additions and 45 deletions.
10 changes: 0 additions & 10 deletions UsbipdGui/App.config
Original file line number Diff line number Diff line change
@@ -1,15 +1,5 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<sectionGroup name="userSettings" type="System.Configuration.UserSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
<section name="UsbipdGui.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowExeDefinition="MachineToLocalUser" requirePermission="false" />
</sectionGroup>
</configSections>
<userSettings>
<UsbipdGui.Properties.Settings>
<setting name="RunAtStartup" serializeAs="String">
<value>False</value>
</setting>
</UsbipdGui.Properties.Settings>
</userSettings>
</configuration>
32 changes: 12 additions & 20 deletions UsbipdGui/App.xaml.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using Microsoft.Win32;
using Microsoft.Win32.TaskScheduler;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Text.RegularExpressions;
Expand All @@ -15,6 +16,7 @@ public partial class App : System.Windows.Application
{
private readonly string _appName = "UsbipdGui";
private readonly string _version = "1.0.0";
private readonly string? _exePath = System.Diagnostics.Process.GetCurrentProcess().MainModule?.FileName;

// Resources
private readonly System.Drawing.Icon _lightThemeIcon = new(
Expand All @@ -27,7 +29,8 @@ public partial class App : System.Windows.Application
GetResourceStream(new Uri("resource/StateAttach.ico", UriKind.Relative)).Stream);

private Usbipd? _usbipd = null;
Settings _settings = new();
private Settings _settings = new();
private bool _startupAtRun = false;
private List<UsbDevice> _ignoredDeviceList = [];
private System.Windows.Forms.NotifyIcon _notifyIcon = new();
private System.Windows.Forms.ContextMenuStrip _contextMenu = new();
Expand Down Expand Up @@ -67,6 +70,8 @@ protected override void OnStartup(StartupEventArgs e)

// Add system eventt handler to switch the theme of notify icon
Microsoft.Win32.SystemEvents.UserPreferenceChanged += SystemEvents_UserPreferenceChanged;

_startupAtRun = StartupSettings.IsRegistered(_appName);
}

private List<UsbDevice> LoadIgnoredUsbIdList()
Expand Down Expand Up @@ -242,7 +247,7 @@ private ToolStripMenuItem BuildSettingsItem()
{
ToolStripMenuItem startupItem = new("Run at startup")
{
Checked = _settings.RunAtStartup,
Checked = _startupAtRun,
};
startupItem.MouseUp += (sender, e) =>
{
Expand Down Expand Up @@ -434,34 +439,21 @@ private void OnLeftClickToRemoveFromIgnoreList(object? sender, EventArgs e)

private void OnLeftClickToToggleRunAtStartup(object? sender, EventArgs e)
{
string appName = System.Diagnostics.Process.GetCurrentProcess().ProcessName ?? _appName;
string? appPath = System.Diagnostics.Process.GetCurrentProcess().MainModule?.FileName;
if (String.IsNullOrWhiteSpace(appPath))
if (String.IsNullOrWhiteSpace(_exePath))
{
return;
}

bool nextStateRunAtStartup = !_settings.RunAtStartup;

using RegistryKey? key = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run", true);
bool nextStateRunAtStartup = !_startupAtRun;
if (nextStateRunAtStartup)
{
// Add Application to Run registory to run at startup
key?.SetValue(appName, appPath);
StartupSettings.RegisterTask(_appName, _exePath);
}
else
{
// Remove Application from Run registory
if (key?.GetValue(appName) is not null)
{
key?.DeleteValue(appName);
}
StartupSettings.RemoveTask(_appName);
}
Debug.WriteLine($"PATH={key} KEY={appName} VALUE={key?.GetValue(appName)}");
key?.Close();

_settings.RunAtStartup = nextStateRunAtStartup;
_settings.Save();
_startupAtRun = StartupSettings.IsRegistered(_appName);
}

private void OnLeftClickToBindDevice(object? sender, EventArgs e)
Expand Down
12 changes: 0 additions & 12 deletions UsbipdGui/Properties/Settings.Designer.cs

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

3 changes: 0 additions & 3 deletions UsbipdGui/Properties/Settings.settings
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,5 @@
<Setting Name="IgnoredUsbIds" Type="System.Collections.Specialized.StringCollection" Scope="User">
<Value Profile="(Default)" />
</Setting>
<Setting Name="RunAtStartup" Type="System.Boolean" Scope="User">
<Value Profile="(Default)">False</Value>
</Setting>
</Settings>
</SettingsFile>
51 changes: 51 additions & 0 deletions UsbipdGui/StartupSettings.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
using Microsoft.Win32.TaskScheduler;
using System;
using System.Diagnostics;

namespace UsbipdGui
{
internal static class StartupSettings
{
public static bool IsRegistered(in string appName)
{
using TaskService taskService = new();
return taskService.GetTask(appName) is not null;
}

public static void RegisterTask(in string appName, in string exePath)
{
try
{
using TaskService taskService = new();
if (taskService.GetTask(appName) is not null)
{
// already registered
return;
}
TaskDefinition taskDefinition = taskService.NewTask();
taskDefinition.RegistrationInfo.Description = appName;
taskDefinition.Principal.RunLevel = TaskRunLevel.Highest; // Run as administrator
taskDefinition.Triggers.Add(new LogonTrigger()); // Run at startup
taskDefinition.Actions.Add(new ExecAction(exePath));
taskService.RootFolder.RegisterTaskDefinition(appName, taskDefinition);
}
catch (Exception ex)
{
Debug.WriteLine($"Catch exception {ex}");
}
}

public static void RemoveTask(in string appName)
{
try
{
using TaskService taskService = new();
taskService.RootFolder.DeleteTask(appName);
}
catch (Exception ex)
{
Debug.WriteLine($"Catch exception {ex}");
}
}
}
}
4 changes: 4 additions & 0 deletions UsbipdGui/UsbipdGui.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,10 @@
<ApplicationIcon>resource\UsbipdGuiApp.ico</ApplicationIcon>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="TaskScheduler" Version="2.10.1" />
</ItemGroup>

<ItemGroup>
<Resource Include="resource\StateAttach.ico" />
<Resource Include="resource\StateBind.ico" />
Expand Down

0 comments on commit acda121

Please sign in to comment.