71 lines
2.7 KiB
C#
71 lines
2.7 KiB
C#
using System.IO;
|
||
using System.IO.Pipes;
|
||
|
||
namespace DeskCore;
|
||
|
||
/// <summary>
|
||
/// Befehlszeile von DeskCore, z. B. für Desktop-Verknüpfungen und Skripte:
|
||
/// DeskCore.exe --launch "Arbeit" Start-Gruppe starten
|
||
/// DeskCore.exe --snapshot "Name" Box-Anordnung wiederherstellen
|
||
/// DeskCore.exe --toggle-desktop Desktop-Icons und Boxen ein-/ausblenden
|
||
/// DeskCore.exe --peek Boxen vor alle Fenster holen
|
||
/// DeskCore.exe --minimized im Infobereich starten
|
||
/// Läuft DeskCore schon, wird der Befehl an die laufende Instanz weitergereicht.
|
||
/// </summary>
|
||
public static class Commands
|
||
{
|
||
private const string PipeName = "DeskCore.Befehle";
|
||
private const char Separator = '\u001F';
|
||
|
||
public static string? Value(string[] args, string name)
|
||
{
|
||
int i = Array.FindIndex(args, a => a.Equals(name, StringComparison.OrdinalIgnoreCase));
|
||
return i >= 0 && i + 1 < args.Length ? args[i + 1] : null;
|
||
}
|
||
|
||
public static bool Has(string[] args, string name) => args.Any(a => a.Equals(name, StringComparison.OrdinalIgnoreCase));
|
||
|
||
/// <summary>Soll für diesen Aufruf das Hauptfenster erscheinen?</summary>
|
||
public static bool WantsWindow(string[] args) =>
|
||
!Has(args, "--minimized") && Value(args, "--launch") is null && Value(args, "--snapshot") is null &&
|
||
!Has(args, "--toggle-desktop") && !Has(args, "--peek");
|
||
|
||
/// <summary>An die laufende Instanz senden.</summary>
|
||
public static bool Send(string[] args)
|
||
{
|
||
try
|
||
{
|
||
using var client = new NamedPipeClientStream(".", PipeName, PipeDirection.Out);
|
||
client.Connect(3000);
|
||
using var w = new StreamWriter(client);
|
||
w.Write(string.Join(Separator, args));
|
||
w.Flush();
|
||
return true;
|
||
}
|
||
catch { return false; }
|
||
}
|
||
|
||
/// <summary>
|
||
/// Empfängt Befehle weiterer Aufrufe (im Hintergrund). Die Pipe ist standardmäßig nur für den
|
||
/// eigenen Benutzer beschreibbar – andere Benutzer können DeskCore keine Befehle schicken.
|
||
/// </summary>
|
||
public static void Listen(Action<string[]> onCommand)
|
||
{
|
||
new Thread(() =>
|
||
{
|
||
while (true)
|
||
{
|
||
try
|
||
{
|
||
using var server = new NamedPipeServerStream(PipeName, PipeDirection.In, 1);
|
||
server.WaitForConnection();
|
||
using var r = new StreamReader(server);
|
||
var text = r.ReadToEnd();
|
||
onCommand(text.Length == 0 ? [] : text.Split(Separator));
|
||
}
|
||
catch { Thread.Sleep(500); }
|
||
}
|
||
}) { IsBackground = true, Name = "Befehle" }.Start();
|
||
}
|
||
}
|