-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProgram.cs
83 lines (72 loc) · 2.02 KB
/
Program.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
using H.NotifyIcon.Core;
using Microsoft.Win32;
using System.Diagnostics;
using System.Drawing;
Process[] existingProcesses = Process.GetProcessesByName(Process.GetCurrentProcess().ProcessName);
if (existingProcesses.Length > 1)
{
Environment.Exit(0);
}
using Process WSLSleep = new Process();
WSLSleep.StartInfo.FileName = "wsl.exe";
WSLSleep.StartInfo.Arguments = "sleep infinity";
WSLSleep.StartInfo.CreateNoWindow = true;
WSLSleep.StartInfo.UseShellExecute = false;
WSLSleep.Start();
var executableFileName = Process.GetCurrentProcess().MainModule?.FileName;
if(executableFileName is null)
{
Environment.Exit(1);
}
using var icon = Icon.ExtractAssociatedIcon(executableFileName);
if (icon is null)
{
Environment.Exit(1);
}
using var trayIcon = new TrayIconWithContextMenu
{
Icon = icon.Handle,
ToolTip = "WSL Keep Alive"
};
var AutoStartMenuItem = new PopupMenuItem("Start on boot", (sender, _) =>
{
if(sender is not PopupMenuItem) return;
var menuItem = (PopupMenuItem)sender;
menuItem.Checked = ToggleAutoStart();
});
trayIcon.ContextMenu = new PopupMenu
{
Items = {
AutoStartMenuItem,
new PopupMenuItem("Exit", (_,_) =>
{
WSLSleep.Kill();
WSLSleep.Dispose();
trayIcon.Dispose();
Environment.Exit(0);
})
}
};
AutoStartMenuItem.Checked = GetAutoStart();
trayIcon.Create();
WSLSleep.WaitForExit();
bool GetAutoStart()
{
using var key = Registry.CurrentUser.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", true);
return key?.GetValue(Process.GetCurrentProcess().ProcessName) != null;
}
bool ToggleAutoStart()
{
using var key = Registry.CurrentUser.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", true);
if(key is null) return false;
if (GetAutoStart())
{
key.DeleteValue(Process.GetCurrentProcess().ProcessName);
return false;
}
else
{
key.SetValue(Process.GetCurrentProcess().ProcessName, $"\"{executableFileName}\"");
return true;
}
}