Setup-Assistent und Update-Abfrage bei jedem Start

Die heruntergeladene Datei ist ein Setup: Sprache, Ordner (nur ohne Admin-Rechte beschreibbar),
Verknuepfungen, Fortschritt, Fertig-Seite; Ordner steht in der Registry. Deinstallieren loescht im
gewaehlten Ordner nur die eigenen Dateien. Beim Start fragt der Launcher nach neuen Updates
(Launcher und Mod).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-28 20:01:27 +01:00
co-authored by Claude Opus 5.5
parent 884492f665
commit 5fd162fecb
10 changed files with 461 additions and 109 deletions
+84 -101
View File
@@ -5,9 +5,10 @@ using Microsoft.Win32;
namespace BSO.Launcher;
/// <summary>
/// Installation wie bei Discord (wie beim MSCO Launcher): die heruntergeladene .exe installiert sich selbst ohne
/// Admin-Rechte nach %LocalAppData%\Programs\BSO Launcher, legt Verknuepfungen (Desktop, Startmenue) an, traegt sich unter
/// "Apps &amp; Features" ein (Deinstallieren) und startet dann den installierten Launcher.
/// Installation: die heruntergeladene .exe (BSO-Launcher-Setup.exe) ist zugleich das Setup (SetupForm). Sie kopiert sich
/// ohne Admin-Rechte in den gewaehlten Ordner (Standard %LocalAppData%\Programs\BSO Launcher), legt die gewaehlten
/// Verknuepfungen an, traegt sich unter "Apps &amp; Features" ein (Deinstallieren) und startet dann den installierten Launcher.
/// Der Ordner steht in der Registry (InstallLocation) - danach aktualisiert sich der Launcher dort selbst.
/// </summary>
public static class Installer
{
@@ -15,15 +16,57 @@ public static class Installer
const string ExeName = "BSO-Launcher.exe";
const string UninstallKey = @"Software\Microsoft\Windows\CurrentVersion\Uninstall\BSO-Launcher";
public static string InstallDir =>
public static string DefaultDir =>
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Programs", AppName);
/// <summary>Ordner der bestehenden Installation (aus "Apps &amp; Features") oder null.</summary>
public static string? RegisteredDir
{
get
{
try
{
using var key = Registry.CurrentUser.OpenSubKey(UninstallKey);
return key?.GetValue("InstallLocation") is string dir && dir.Length > 0 ? dir : null;
}
catch { return null; }
}
}
public static string InstallDir => RegisteredDir ?? DefaultDir;
public static string InstalledExe => Path.Combine(InstallDir, ExeName);
static string Self => Environment.ProcessPath ?? Application.ExecutablePath;
public static long SelfSize => new FileInfo(Self).Length;
static string StartMenuShortcut =>
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Programs), AppName + ".lnk");
static string DesktopShortcut =>
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory), AppName + ".lnk");
public static bool HasStartMenuShortcut => File.Exists(StartMenuShortcut);
public static bool HasDesktopShortcut => File.Exists(DesktopShortcut);
/// <summary>Gewaehlter Ordner -> Installationsordner: immer ein eigener Unterordner "BSO Launcher" (beim Deinstallieren
/// wird nur der geloescht, nie z.B. "D:\Spiele").</summary>
public static string NormalizeDir(string chosen)
{
string dir = Path.GetFullPath(Environment.ExpandEnvironmentVariables(chosen.Trim().Trim('"')));
return string.Equals(Path.GetFileName(dir.TrimEnd('\\')), AppName, StringComparison.OrdinalIgnoreCase) ? dir : Path.Combine(dir, AppName);
}
/// <summary>Darf dieser Benutzer dort schreiben? (Programme ohne Admin-Rechte - auch fuer die Selbst-Updates noetig.)</summary>
public static string? CheckWritable(string dir)
{
try
{
Directory.CreateDirectory(dir);
string probe = Path.Combine(dir, ".bso-write-test");
File.WriteAllText(probe, "");
File.Delete(probe);
return null;
}
catch (UnauthorizedAccessException) { return "Keine Schreibrechte in diesem Ordner - bitte einen Ordner waehlen, in dem du ohne Admin-Rechte schreiben darfst"; }
catch (Exception e) { return "Ordner nicht nutzbar: " + e.Message; }
}
/// <summary>Laeuft gerade die installierte Kopie?</summary>
public static bool RunningInstalled =>
@@ -35,23 +78,19 @@ public static class Installer
return FileVersionInfo.GetVersionInfo(InstalledExe).ProductVersion?.Split('+')[0];
}
/// <summary>Muss installiert (oder aktualisiert) werden? false = installierte Version ist gleich/neuer.</summary>
public static bool NeedsInstall()
{
string? installed = InstalledVersion();
return installed == null || SelfUpdate.IsNewer(SelfUpdate.CurrentVersion, installed);
}
/// <summary>Installieren. progress(0..1, Text).</summary>
public static void Install(Action<double, string> progress)
/// <summary>Installieren (auch Update/Neu-Installation, auch in einen anderen Ordner). progress(0..1, Text).</summary>
public static void Install(string dir, bool desktop, bool startMenu, Action<double, string> progress)
{
string? oldExe = File.Exists(InstalledExe) ? InstalledExe : null;
string exe = Path.Combine(dir, ExeName);
progress(0.1, Lang.T("Laufenden Launcher schliessen …"));
foreach (var p in Process.GetProcessesByName("BSO-Launcher"))
{
try
{
if (p.Id == Environment.ProcessId) continue;
if (!string.Equals(p.MainModule?.FileName, InstalledExe, StringComparison.OrdinalIgnoreCase)) continue;
string? file = p.MainModule?.FileName;
if (!string.Equals(file, exe, StringComparison.OrdinalIgnoreCase) && !string.Equals(file, oldExe, StringComparison.OrdinalIgnoreCase)) continue;
p.CloseMainWindow();
if (!p.WaitForExit(3000)) p.Kill(true);
}
@@ -59,37 +98,49 @@ public static class Installer
}
progress(0.3, Lang.T("Dateien kopieren …"));
Directory.CreateDirectory(InstallDir);
string tmp = InstalledExe + ".new";
Directory.CreateDirectory(dir);
string tmp = exe + ".new";
File.Copy(Self, tmp, true);
File.Move(tmp, InstalledExe, true);
File.Move(tmp, exe, true);
// Vorher woanders installiert: die alte Kopie wegraeumen (nur unsere Dateien, den Ordner nur wenn leer)
if (oldExe != null && !string.Equals(oldExe, exe, StringComparison.OrdinalIgnoreCase)) RemoveFiles(Path.GetDirectoryName(oldExe)!);
progress(0.6, Lang.T("Verknuepfungen anlegen …"));
CreateShortcut(StartMenuShortcut);
CreateShortcut(DesktopShortcut);
Register(dir); // ab hier zeigen InstallDir/InstalledExe auf den neuen Ordner
if (startMenu) CreateShortcut(StartMenuShortcut); else TryDelete(StartMenuShortcut);
if (desktop) CreateShortcut(DesktopShortcut); else TryDelete(DesktopShortcut);
progress(0.8, Lang.T("Registrieren …"));
Register();
progress(1.0, Lang.T("Fertig"));
}
static void TryDelete(string file) { try { File.Delete(file); } catch { } }
/// <summary>Unsere Dateien im Installationsordner loeschen, den Ordner nur wenn er danach leer ist.</summary>
static void RemoveFiles(string dir)
{
foreach (string name in new[] { ExeName, ExeName + ".old", ExeName + ".new" }) TryDelete(Path.Combine(dir, name));
try { if (!Directory.EnumerateFileSystemEntries(dir).Any()) Directory.Delete(dir); } catch { }
}
/// <summary>Eintrag unter "Apps &amp; Features" (bzw. dessen Version nach einem Selbst-Update).</summary>
public static void Register()
public static void Register(string? dir = null)
{
try
{
dir ??= InstallDir;
string exe = Path.Combine(dir, ExeName);
using var key = Registry.CurrentUser.CreateSubKey(UninstallKey);
key.SetValue("DisplayName", AppName);
key.SetValue("DisplayVersion", SelfUpdate.CurrentVersion);
key.SetValue("Publisher", "MBM.wtf");
key.SetValue("DisplayIcon", InstalledExe + ",0");
key.SetValue("InstallLocation", InstallDir);
key.SetValue("UninstallString", $"\"{InstalledExe}\" --uninstall");
key.SetValue("QuietUninstallString", $"\"{InstalledExe}\" --uninstall --quiet");
key.SetValue("DisplayIcon", exe + ",0");
key.SetValue("InstallLocation", dir);
key.SetValue("UninstallString", $"\"{exe}\" --uninstall");
key.SetValue("QuietUninstallString", $"\"{exe}\" --uninstall --quiet");
key.SetValue("URLInfoAbout", Api.BaseUrl);
key.SetValue("NoModify", 1, RegistryValueKind.DWord);
key.SetValue("NoRepair", 1, RegistryValueKind.DWord);
try { key.SetValue("EstimatedSize", (int)(new FileInfo(InstalledExe).Length / 1024), RegistryValueKind.DWord); } catch { }
try { key.SetValue("EstimatedSize", (int)(new FileInfo(exe).Length / 1024), RegistryValueKind.DWord); } catch { }
}
catch { /* Eintrag ist nur Komfort */ }
}
@@ -119,8 +170,9 @@ public static class Installer
Process.Start(start);
}
/// <summary>Ordner/Dateien loeschen, sobald dieser Prozess beendet ist (seine .exe ist bis dahin gesperrt).</summary>
static void RemoveAfterExit(params string[] paths)
/// <summary>Ordner/Dateien loeschen, sobald dieser Prozess beendet ist (seine .exe ist bis dahin gesperrt). Danach
/// emptyDir entfernen, aber nur wenn er leer ist (der Benutzer hat den Ordner gewaehlt - fremde Dateien bleiben).</summary>
static void RemoveAfterExit(string emptyDir, params string[] paths)
{
static string Quote(string p) => "'" + p.Replace("'", "''") + "'";
string list = string.Join(",", paths.Where(p => !string.IsNullOrWhiteSpace(p)).Select(Quote));
@@ -128,7 +180,8 @@ public static class Installer
$"Wait-Process -Id {Environment.ProcessId} -ErrorAction SilentlyContinue; " +
$"foreach ($i in 1..30) {{ $left = $false; foreach ($p in @({list})) {{ " +
"if (Test-Path -LiteralPath $p) { Remove-Item -LiteralPath $p -Recurse -Force -ErrorAction SilentlyContinue; " +
"if (Test-Path -LiteralPath $p) { $left = $true } } }; if (-not $left) { break }; Start-Sleep -Seconds 1 }";
"if (Test-Path -LiteralPath $p) { $left = $true } } }; if (-not $left) { break }; Start-Sleep -Seconds 1 }; " +
$"$d = {Quote(emptyDir)}; if ((Test-Path -LiteralPath $d) -and -not (Get-ChildItem -LiteralPath $d -Force)) {{ Remove-Item -LiteralPath $d -Force }}";
var psi = new ProcessStartInfo("powershell.exe") { CreateNoWindow = true, UseShellExecute = false, WindowStyle = ProcessWindowStyle.Hidden };
foreach (string a in new[] { "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-WindowStyle", "Hidden", "-Command", script })
psi.ArgumentList.Add(a);
@@ -160,7 +213,7 @@ public static class Installer
try { File.Delete(DesktopShortcut); } catch { }
try { Registry.CurrentUser.DeleteSubKeyTree(UninstallKey, false); } catch { }
// Die laufende .exe laesst sich nicht selbst loeschen: aufraeumen, sobald dieser Prozess beendet ist
RemoveAfterExit(dir, Settings.Folder);
RemoveAfterExit(dir, Path.Combine(dir, ExeName), Path.Combine(dir, ExeName + ".old"), Path.Combine(dir, ExeName + ".new"), Settings.Folder);
if (!quiet)
MessageBox.Show(Lang.T(problems.Count == 0
? "BSO wurde komplett deinstalliert."
@@ -175,73 +228,3 @@ public static class Installer
return s == null ? null : Image.FromStream(s);
}
}
/// <summary>Kleines Installationsfenster (wie der Discord-Installer): Logo, Status, Fortschrittsbalken.</summary>
public sealed class InstallForm : Form
{
readonly Label status = new();
double progress;
string? error;
public InstallForm()
{
FormBorderStyle = FormBorderStyle.None;
StartPosition = FormStartPosition.CenterScreen;
ClientSize = new Size(420, 260);
BackColor = Color.FromArgb(0x15, 0x19, 0x22);
ShowInTaskbar = true;
Text = "BSO Launcher wird installiert";
DoubleBuffered = true;
try { Icon = Icon.ExtractAssociatedIcon(Environment.ProcessPath ?? Application.ExecutablePath); } catch { }
status.ForeColor = Color.FromArgb(0x8b, 0x95, 0xa5);
status.Font = new Font("Segoe UI", 9.5f);
status.TextAlign = ContentAlignment.MiddleCenter;
status.SetBounds(20, 178, 380, 24);
status.Text = Lang.T("Vorbereiten …");
Controls.Add(status);
Shown += async (_, _) => await Run();
}
protected override void OnPaint(PaintEventArgs e)
{
var g = e.Graphics;
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
using (var border = new Pen(Color.FromArgb(0x26, 0x2c, 0x38))) g.DrawRectangle(border, 0, 0, Width - 1, Height - 1);
var logo = Installer.Logo();
if (logo != null) g.DrawImage(logo, (Width - 72) / 2, 34, 72, 72);
using var title = new Font("Segoe UI", 15f, FontStyle.Bold);
TextRenderer.DrawText(g, "BSO Launcher", title, new Rectangle(0, 116, Width, 34), Color.White, TextFormatFlags.HorizontalCenter);
using var sub = new Font("Segoe UI", 9f);
TextRenderer.DrawText(g, "Bus Simulator Online", sub, new Rectangle(0, 148, Width, 22), Color.FromArgb(0x8b, 0x95, 0xa5), TextFormatFlags.HorizontalCenter);
// Fortschrittsbalken
var bar = new Rectangle(40, 214, Width - 80, 8);
using (var back = new SolidBrush(Color.FromArgb(0x23, 0x2a, 0x36))) g.FillRectangle(back, bar);
if (progress > 0)
{
var fill = new Rectangle(bar.X, bar.Y, (int)(bar.Width * progress), bar.Height);
using var brush = new System.Drawing.Drawing2D.LinearGradientBrush(bar, Color.FromArgb(0x1f, 0x6f, 0xe5), Color.FromArgb(0x5e, 0xe4, 0xff), 0f);
g.FillRectangle(error != null ? Brushes.IndianRed : brush, fill);
}
}
async Task Run()
{
try
{
await Task.Run(() => Installer.Install((p, text) => BeginInvoke(() => { progress = p; status.Text = text; Invalidate(); })));
await Task.Delay(400);
Installer.StartInstalled();
Close();
}
catch (Exception e)
{
error = e.Message;
status.ForeColor = Color.FromArgb(0xff, 0x8a, 0x8d);
status.Text = Lang.T("Installation fehlgeschlagen: " + e.Message);
Invalidate();
await Task.Delay(6000);
Close();
}
}
}