LNK Screen Manager v1.1 - première version validée

- Allumer / éteindre chaque écran et activer / couper le HDR en un clic
  (API Windows CCD, disposition, résolution et fréquence mémorisées).
- Profils (clic = appliquer, raccourcis bureau, ligne de commande --profile).
- Noms personnalisés des écrans, mini-carte de la disposition, identification.
- Icône près de l'heure avec menu (profils, écrans, HDR) ; fermeture vers la
  zone de notification désactivable ; lancement au démarrage de Windows.
- Interface sobre (thème sombre plat) ; au repos ~2-4 Mo de RAM, 0 % CPU.
- Compilation sans dépendance avec build.bat (compilateur C# de Windows).
This commit is contained in:
linkatplug committed 2026-11-24 03:47:56 +01:00
commit 92ce5a779b
9 files changed
+2000

No files matched your search

+6
View File
@@ -0,0 +1,6 @@
* text=auto
*.cs text eol=crlf
*.bat text eol=crlf
*.md text eol=lf
*.png binary
*.ico binary
+7
View File
@@ -0,0 +1,7 @@
# Binaires generes par build.bat
/build/
*.exe
*.pdb
# Divers
Thumbs.db
desktop.ini
+30
View File
@@ -0,0 +1,30 @@
# LNK Screen Manager
By LNK Co © 2026 — allumer / éteindre ses écrans et gérer le HDR en un clic, sans passer par les Paramètres Windows.
## Utilisation
- **LNK Screen Manager.exe** : ouvre la fenêtre (interrupteurs *Écran* et *HDR* par écran, mini-carte, profils).
- Fermer la fenêtre (X) la réduit près de l'heure. Clic droit sur l'icône : profils, écrans, HDR. Désactivable dans *Options*.
- Profils : *Nouveau profil* enregistre l'état actuel. Clic = appliquer, clic droit = raccourci bureau / renommer / supprimer.
- Double-clic sur un écran de la mini-carte : l'allumer / l'éteindre.
- Renommer un écran : clic sur son nom (crayon), clic droit sur sa carte, ou clic droit sur l'icône près de l'heure → *Renommer un écran*. Nom vide = nom d'origine.
- En cas de souci : **Win + P → Étendre** rallume tous les écrans.
## Ressources
Au repos (icône près de l'heure) : ~2-4 Mo de RAM, 0 % de processeur (aucun minuteur, aucune tâche de fond active).
La fenêtre n'existe que lorsqu'elle est ouverte : à la fermeture elle est détruite et la mémoire rendue à Windows.
Option *Afficher la disposition* pour masquer la mini-carte.
## Ligne de commande
```
"LNK Screen Manager.exe" --profile "Jeu" applique un profil sans fenêtre
"LNK Screen Manager.exe" --all-on rallume tous les écrans
"LNK Screen Manager.exe" --tray démarre réduit près de l'heure
```
## Sur un autre PC
Windows 10 / 11 uniquement, rien à installer (.NET Framework 4 est inclus dans Windows). Copier l'exe, le lancer, recréer ses profils.
Les données (profils, disposition, options) sont dans `%APPDATA%\LNK Screen Manager`.
## Compiler
`build.bat` (utilise le compilateur C# fourni avec Windows). Sources dans `src\`, icône et logo générés dans `assets\`.
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 41 KiB

BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 32 KiB

+16
View File
@@ -0,0 +1,16 @@
@echo off
rem LNK Screen Manager - compilation (utilise le compilateur C# inclus dans Windows)
setlocal
set CSC=%WINDIR%\Microsoft.NET\Framework64\v4.0.30319\csc.exe
set ROOT=%~dp0
set REFS=/r:System.Windows.Forms.dll /r:System.Drawing.dll /r:System.Core.dll
if not exist "%ROOT%build" mkdir "%ROOT%build"
if not exist "%ROOT%assets" mkdir "%ROOT%assets"
rem 1) passe sans icone, qui dessine l'icone et le logo
"%CSC%" /nologo /target:winexe /optimize /out:"%ROOT%build\stage1.exe" %REFS% "%ROOT%src\*.cs" || exit /b 1
start "" /wait "%ROOT%build\stage1.exe" --make-icon "%ROOT%assets" || exit /b 1
rem 2) exe final avec icone integree
"%CSC%" /nologo /target:winexe /optimize /win32icon:"%ROOT%assets\app.ico" /resource:"%ROOT%assets\app.ico",LnkScreenManager.app.ico /out:"%ROOT%LNK Screen Manager.exe" %REFS% "%ROOT%src\*.cs" || exit /b 1
echo Build OK : "%ROOT%LNK Screen Manager.exe"
+770
View File
@@ -0,0 +1,770 @@
// LNK Screen Manager - icone pres de l'heure (controleur), fenetre, options, demarrage.
// By LNK Co (c) 2026
//
// Sobriete des ressources :
// - au repos l'appli n'est qu'une icone pres de l'heure : aucun minuteur, aucune tache de fond qui tourne ;
// - la fenetre n'existe que quand elle est ouverte ; fermee, elle est detruite et la memoire rendue a Windows ;
// - les menus sont construits a l'ouverture puis liberes.
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Threading;
using System.Windows.Forms;
using Microsoft.Win32;
[assembly: AssemblyTitle("LNK Screen Manager")]
[assembly: AssemblyDescription("Allumer / éteindre les écrans et gérer le HDR")]
[assembly: AssemblyCompany("LNK Co")]
[assembly: AssemblyProduct("LNK Screen Manager")]
[assembly: AssemblyCopyright("© 2026 LNK Co")]
[assembly: AssemblyVersion("1.1.0.0")]
[assembly: AssemblyFileVersion("1.1.0.0")]
namespace LnkScreenManager
{
// ------------------------------------------------------------------ Options (settings.ini dans %APPDATA%)
static class Settings
{
static Dictionary<string, string> d;
static string FilePath { get { return AppData.File("settings.ini"); } }
static void Load()
{
if (d != null) return;
d = new Dictionary<string, string>();
try
{
if (File.Exists(FilePath))
foreach (var l in File.ReadAllLines(FilePath))
{
int i = l.IndexOf('=');
if (i > 0) d[l.Substring(0, i).Trim()] = l.Substring(i + 1).Trim();
}
}
catch { }
}
static bool Get(string k, bool def) { Load(); string v; return d.TryGetValue(k, out v) ? v == "1" : def; }
static void Set(string k, bool v) { Load(); d[k] = v ? "1" : "0"; try { File.WriteAllLines(FilePath, d.Select(kv => kv.Key + "=" + kv.Value)); } catch { } }
public static bool TrayOnClose { get { return Get("TrayOnClose", true); } set { Set("TrayOnClose", value); } }
public static bool TrayHintShown { get { return Get("TrayHintShown", false); } set { Set("TrayHintShown", value); } }
public static bool NotifyChanges { get { return Get("NotifyChanges", true); } set { Set("NotifyChanges", value); } }
public static bool ShowMap { get { return Get("ShowMap", true); } set { Set("ShowMap", value); } }
}
static class Startup
{
const string RunKey = @"Software\Microsoft\Windows\CurrentVersion\Run";
static string Cmd { get { return "\"" + Application.ExecutablePath + "\" --tray"; } }
public static bool Enabled
{
get { try { using (var k = Registry.CurrentUser.OpenSubKey(RunKey)) return k != null && k.GetValue(Brand.Name) != null; } catch { return false; } }
set
{
using (var k = Registry.CurrentUser.CreateSubKey(RunKey))
{
if (value) k.SetValue(Brand.Name, Cmd); else k.DeleteValue(Brand.Name, false);
}
}
}
/// Si l'exe a ete deplace, met a jour le chemin de demarrage (n'ecrit que si necessaire).
public static void RefreshPath()
{
try
{
using (var k = Registry.CurrentUser.OpenSubKey(RunKey, true))
{
if (k == null) return;
var v = k.GetValue(Brand.Name) as string;
if (v != null && v != Cmd) k.SetValue(Brand.Name, Cmd);
}
}
catch { }
}
}
// ------------------------------------------------------------------ Controleur : icone pres de l'heure + etat + actions
class TrayApp : ApplicationContext
{
readonly NotifyIcon tray = new NotifyIcon();
readonly ContextMenuStrip menu = Menus.Create();
readonly Control sync = new Control();
readonly System.Windows.Forms.Timer debounce = new System.Windows.Forms.Timer { Interval = 600 };
MainForm form;
DateTime lastRefresh = DateTime.MinValue;
public List<Monitor> Mons = new List<Monitor>();
public List<Profile> ProfileList = new List<Profile>();
public bool Busy, StatusError, Exiting;
public string Status = "";
public event Action Changed;
public TrayApp(bool hidden)
{
var h = sync.Handle; // file de messages pour revenir sur le thread de l'interface
tray.Icon = LogoArt.AppIcon(SystemInformation.SmallIconSize.Width);
tray.Text = Brand.Name;
tray.ContextMenuStrip = menu;
menu.Opening += (s, e) => { Refresh(); BuildTrayMenu(); e.Cancel = false; };
menu.Closed += (s, e) => { if (form == null) Post(() => { Menus.Clear(menu); Win.Trim(); }); };
tray.MouseClick += (s, e) => { if (e.Button == MouseButtons.Left) ShowMain(); };
tray.BalloonTipClicked += (s, e) => ShowMain();
tray.Visible = true;
debounce.Tick += (s, e) => { debounce.Stop(); Refresh(); };
SystemEvents.DisplaySettingsChanged += OnDisplayChanged;
if (hidden) Post(Win.Trim); else ShowMain(); // Post : apres l'initialisation de la boucle de messages
}
public void Post(Action a) { try { if (sync.IsHandleCreated) sync.BeginInvoke(a); } catch { } }
// fenetre fermee = rien a mettre a jour : on ne fait rien du tout
void OnDisplayChanged(object s, EventArgs e) { if (form != null) Post(() => { debounce.Stop(); debounce.Start(); }); }
// ------------------------------------------------ etat
public void Refresh()
{
if (Busy) return;
try { Mons = ReadingOrder(Displays.List()); ProfileList = Profiles.Load(); }
catch (Exception ex) { SetStatus(ex.Message, true); return; }
lastRefresh = DateTime.Now;
tray.Text = Brand.Name + "\n" + Summary;
if (Changed != null) Changed();
}
public void RefreshIfStale() { if ((DateTime.Now - lastRefresh).TotalMilliseconds > 1500) Refresh(); }
public void RefreshIfOpen() { if (form != null) Refresh(); }
public string Summary
{
get
{
int on = Mons.Count(m => m.Active), hdr = Mons.Count(m => m.Active && m.HdrOn);
return on + " / " + Mons.Count + " écrans allumés" + (hdr > 0 ? " · HDR " + hdr : "");
}
}
public void SetStatus(string s, bool error) { Status = s; StatusError = error; if (Changed != null) Changed(); }
public int Number(Monitor m) { return Mons.IndexOf(m) + 1; }
public static string Detail(Monitor m)
{
Rectangle r; int hz;
bool known = Layout.Bounds(m, out r, out hz);
string res = known ? r.Width + " × " + r.Height + (hz > 0 ? " · " + hz + " Hz" : "") : "";
string d = m.Active ? res + (m.Primary ? " · principal" : "") : "éteint" + (known ? " · " + res : "");
return m.HasCustomName ? m.Model + " · " + d : d;
}
public bool Matches(Profile p)
{
bool any = false;
foreach (var m in Mons)
{
bool[] v;
if (!p.Screens.TryGetValue(m.DevicePath, out v)) continue;
any = true;
if (v[0] != m.Active) return false;
if (m.Active && m.HdrSupported && v[1] != m.HdrOn) return false;
}
return any;
}
/// Ordre de lecture : rangee du haut d'abord, puis de gauche a droite (positions memorisees si eteint).
static List<Monitor> ReadingOrder(List<Monitor> list)
{
var withR = list.Select(m =>
{
Rectangle r; int hz;
bool k = Layout.Bounds(m, out r, out hz);
return Tuple.Create(m, k ? r : new Rectangle(int.MaxValue / 4, 0, 1, 1));
}).OrderBy(t => t.Item2.Y + t.Item2.Height / 2).ToList();
var result = new List<Monitor>();
var row = new List<Tuple<Monitor, Rectangle>>();
int rowCenter = 0, rowHalf = 0;
foreach (var t in withR)
{
int cy = t.Item2.Y + t.Item2.Height / 2;
if (row.Count > 0 && cy - rowCenter > rowHalf) { result.AddRange(row.OrderBy(x => x.Item2.X).Select(x => x.Item1)); row.Clear(); }
if (row.Count == 0) { rowCenter = cy; rowHalf = Math.Max(1, t.Item2.Height / 2); }
row.Add(t);
}
result.AddRange(row.OrderBy(x => x.Item2.X).Select(x => x.Item1));
return result;
}
// ------------------------------------------------ actions (executees hors du thread de l'interface)
public void Run(string doing, Action a, string done)
{
if (Busy) return;
Busy = true; SetStatus(doing, false);
new Thread(() =>
{
string err = null;
try { a(); } catch (Exception ex) { err = ex.Message; }
Post(() =>
{
Busy = false;
Refresh();
if (err != null)
{
SetStatus(err, true);
if (form != null) MessageBox.Show(form, err, Brand.Name, MessageBoxButtons.OK, MessageBoxIcon.Warning);
else tray.ShowBalloonTip(4000, Brand.Name, err, ToolTipIcon.Warning);
}
else
{
SetStatus(done, false);
if (form == null && Settings.NotifyChanges) tray.ShowBalloonTip(2000, Brand.Name, done, ToolTipIcon.None);
}
if (form == null) Win.Trim();
});
}) { IsBackground = true }.Start();
}
public void ToggleScreen(Monitor m, bool on)
{
var target = Mons.Where(x => x.Active).Select(x => x.DevicePath).ToList();
if (on) { if (!target.Contains(m.DevicePath)) target.Add(m.DevicePath); }
else target.Remove(m.DevicePath);
if (target.Count == 0) { SetStatus("Il faut garder au moins un écran allumé.", true); Refresh(); return; }
string path = m.DevicePath, name = m.Name;
Run((on ? "Allumage de " : "Extinction de ") + name + "…",
() => { Displays.SetActive(target); Displays.WaitFor(l => l.Any(x => x.DevicePath == path && x.Active == on)); },
name + (on ? " allumé." : " éteint."));
}
public void SetHdr(Monitor m, bool on)
{
string name = m.Name;
Run("HDR…", () => { Displays.SetHdr(m, on); Thread.Sleep(300); }, "HDR " + (on ? "activé" : "coupé") + " sur " + name + ".");
}
public void ApplyProfile(Profile p) { Run("Profil « " + p.Name + " »…", () => Profiles.Apply(p), "Profil « " + p.Name + " » appliqué."); }
public void AllOn() { Run("Allumage de tous les écrans…", () => { Displays.AllOn(); Thread.Sleep(1500); }, "Tous les écrans sont allumés."); }
public void AllHdrOff()
{
Run("Coupure du HDR…", () => { foreach (var m in Displays.List().Where(x => x.Active && x.HdrOn)) Displays.SetHdr(m, false); Thread.Sleep(300); }, "HDR coupé partout.");
}
public void Identify(Monitor only)
{
Refresh();
foreach (var m in Mons)
{
if (!m.Active || (only != null && m.DevicePath != only.DevicePath)) continue;
var sc = Screen.AllScreens.FirstOrDefault(s => s.DeviceName == m.GdiName);
if (sc != null) new IdentifyForm(sc.Bounds, Number(m), m.HasCustomName ? m.Name + " (" + m.Model + ")" : m.Name).Show();
}
}
IWin32Window Owner { get { return form != null && form.Visible ? form : null; } }
public void RenameScreen(Monitor m)
{
if (m == null) return;
string n = Dialogs.Prompt(Owner, "Renommer l'écran", "Nom pour « " + m.Model + " » (vide = nom d'origine) :", m.HasCustomName ? m.Name : "");
if (n == null) return;
try { Names.Set(m.DevicePath, n); Refresh(); SetStatus(n.Length == 0 ? m.Model + " a repris son nom d'origine." : "Écran renommé en « " + n + " ».", false); }
catch (Exception ex) { SetStatus("Nom non enregistré : " + ex.Message, true); }
}
public void ResetScreenName(Monitor m) { try { Names.Set(m.DevicePath, ""); Refresh(); } catch (Exception ex) { SetStatus(ex.Message, true); } }
// ------------------------------------------------ profils
public void NewProfile()
{
string name = Dialogs.Prompt(Owner, "Nouveau profil", "Nom du profil (l'état actuel des écrans est enregistré) :", ProfileList.Count == 0 ? "Jeu" : "");
if (string.IsNullOrEmpty(name)) return;
name = name.Replace("|", "");
var all = Profiles.Load();
int i = all.FindIndex(p => p.Name.Equals(name, StringComparison.OrdinalIgnoreCase));
var np = Profiles.FromCurrent(name);
if (i >= 0) all[i] = np; else all.Add(np);
Profiles.Save(all);
Refresh(); SetStatus("Profil « " + name + " » enregistré.", false);
}
public void ReplaceProfile(Profile p)
{
var all = Profiles.Load(); int i = all.FindIndex(x => x.Name == p.Name);
if (i >= 0) { all[i] = Profiles.FromCurrent(p.Name); Profiles.Save(all); }
Refresh(); SetStatus("Profil « " + p.Name + " » mis à jour.", false);
}
public void RenameProfile(Profile p)
{
string n = Dialogs.Prompt(Owner, "Renommer le profil", "Nouveau nom :", p.Name);
if (string.IsNullOrEmpty(n)) return;
var all = Profiles.Load(); var x = all.FirstOrDefault(q => q.Name == p.Name);
if (x != null) { x.Name = n.Replace("|", ""); Profiles.Save(all); }
Refresh();
}
public void DeleteProfile(Profile p)
{
if (MessageBox.Show(Owner, "Supprimer le profil « " + p.Name + " » ?", Brand.Name, MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes) return;
var all = Profiles.Load(); all.RemoveAll(x => x.Name == p.Name); Profiles.Save(all);
Refresh(); SetStatus("Profil supprimé.", false);
}
public void MakeShortcut(string profile)
{
object shell = null, sc = null;
try
{
var t = Type.GetTypeFromProgID("WScript.Shell");
shell = Activator.CreateInstance(t);
string safe = string.Join("_", profile.Split(Path.GetInvalidFileNameChars()));
string lnk = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory), "LNK - " + safe + ".lnk");
sc = t.InvokeMember("CreateShortcut", BindingFlags.InvokeMethod, null, shell, new object[] { lnk });
var st = sc.GetType();
Action<string, object> set = (name, val) => st.InvokeMember(name, BindingFlags.SetProperty, null, sc, new[] { val });
set("TargetPath", Application.ExecutablePath);
set("Arguments", "--profile \"" + profile + "\"");
set("WorkingDirectory", Path.GetDirectoryName(Application.ExecutablePath));
set("IconLocation", Application.ExecutablePath + ",0");
set("Description", Brand.Name + " - profil " + profile);
st.InvokeMember("Save", BindingFlags.InvokeMethod, null, sc, null);
SetStatus("Raccourci « LNK - " + safe + " » créé sur le bureau.", false);
}
catch (Exception ex) { SetStatus("Raccourci impossible : " + ex.Message, true); }
finally
{
if (sc != null) Marshal.FinalReleaseComObject(sc);
if (shell != null) Marshal.FinalReleaseComObject(shell);
}
}
// ------------------------------------------------ menu pres de l'heure
void BuildTrayMenu()
{
Menus.Clear(menu);
menu.Items.Add(Menus.Header(Brand.Name));
if (ProfileList.Count > 0)
{
menu.Items.Add(new ToolStripSeparator());
menu.Items.Add(Menus.Header("Profils"));
foreach (var p0 in ProfileList)
{
var p = p0;
var it = Menus.Item(p.Name, (s, e) => ApplyProfile(p));
it.Checked = Matches(p);
menu.Items.Add(it);
}
}
menu.Items.Add(new ToolStripSeparator());
menu.Items.Add(Menus.Header("Écrans"));
foreach (var m0 in Mons)
{
var m = m0;
var it = Menus.Item(Number(m) + " " + m.Name, (s, e) => ToggleScreen(m, !m.Active));
it.Checked = m.Active;
menu.Items.Add(it);
}
var hdr = Mons.Where(m => m.Active && m.HdrSupported).ToList();
if (hdr.Count > 0)
{
menu.Items.Add(new ToolStripSeparator());
menu.Items.Add(Menus.Header("HDR"));
foreach (var m0 in hdr)
{
var m = m0;
var it = Menus.Item(Number(m) + " " + m.Name, (s, e) => SetHdr(m, !m.HdrOn));
it.Checked = m.HdrOn;
menu.Items.Add(it);
}
}
menu.Items.Add(new ToolStripSeparator());
var ren = Menus.Sub("Renommer un écran");
foreach (var m0 in Mons)
{
var m = m0;
ren.DropDownItems.Add(Menus.Item(Number(m) + " " + m.Name + (m.HasCustomName ? " (" + m.Model + ")" : ""), (s, e) => RenameScreen(m)));
}
menu.Items.Add(ren);
menu.Items.Add(Menus.Item("Tout allumer", (s, e) => AllOn()));
menu.Items.Add(Menus.Item("Identifier les écrans", (s, e) => Identify(null)));
menu.Items.Add(new ToolStripSeparator());
menu.Items.Add(Menus.Item("Ouvrir", (s, e) => ShowMain()));
menu.Items.Add(Menus.Item("Quitter", (s, e) => Exit()));
}
// ------------------------------------------------ fenetre
public void ShowMain()
{
if (Exiting) return;
if (form == null)
{
Refresh();
form = new MainForm(this);
form.FormClosed += (s, e) =>
{
form = null; debounce.Stop();
if (!Exiting) Post(Win.Trim);
};
form.Show();
}
else
{
if (form.WindowState == FormWindowState.Minimized) form.WindowState = FormWindowState.Normal;
}
form.Activate();
}
/// Appele quand l'utilisateur ferme la fenetre (X).
public void OnUserClose()
{
if (!Settings.TrayOnClose) { Exit(); return; }
if (!Settings.TrayHintShown)
{
tray.ShowBalloonTip(5000, Brand.Name, "Toujours disponible près de l'heure (clic droit : profils, écrans, HDR). Désactivable dans Options.", ToolTipIcon.None);
Settings.TrayHintShown = true;
}
}
public void Exit()
{
if (Exiting) return;
Exiting = true;
SystemEvents.DisplaySettingsChanged -= OnDisplayChanged;
tray.Visible = false;
if (form != null) form.Close();
ExitThread();
}
protected override void Dispose(bool disposing)
{
if (disposing) { tray.Dispose(); menu.Dispose(); debounce.Dispose(); sync.Dispose(); }
base.Dispose(disposing);
}
}
// ------------------------------------------------------------------ Fenetre principale (simple vue de l'etat du controleur)
class MainForm : Form
{
readonly TrayApp app;
readonly Panel header = new Panel(), body = new Panel(), footer = new Panel();
readonly SectionHeader secMap = new SectionHeader("Disposition"), secScreens = new SectionHeader("Écrans") { Columns = true }, secProfiles = new SectionHeader("Profils");
readonly LayoutMap map = new LayoutMap();
readonly List<MonitorCard> cards = new List<MonitorCard>();
readonly List<Pill> pills = new List<Pill>();
readonly ContextMenuStrip optionsMenu = Menus.Create(), itemMenu = Menus.Create();
readonly ToolTip tips = new ToolTip();
string pillsSig;
public MainForm(TrayApp app)
{
this.app = app;
Text = Brand.Name; BackColor = Theme.Bg; ForeColor = Theme.Text; Font = Theme.F(9.5f, false);
AutoScaleMode = AutoScaleMode.None; StartPosition = FormStartPosition.CenterScreen;
Icon = LogoArt.AppIcon(Theme.D(32));
ClientSize = new Size(Theme.D(560), Theme.D(560));
MinimumSize = new Size(Theme.D(470), Theme.D(300));
header.Dock = DockStyle.Top; header.Height = Theme.D(52); header.BackColor = Theme.Bg;
header.Paint += PaintHeader;
var bOpt = new IconButton(Glyph.Settings);
var bId = new IconButton(Glyph.Identify);
tips.SetToolTip(bOpt, "Options"); tips.SetToolTip(bId, "Identifier les écrans");
bOpt.Click += (s, e) => optionsMenu.Show(bOpt, new Point(bOpt.Width - optionsMenu.PreferredSize.Width, bOpt.Height + Theme.D(2)));
bId.Click += (s, e) => app.Identify(null);
header.Controls.Add(bOpt); header.Controls.Add(bId);
header.Resize += (s, e) =>
{
int y = (header.Height - bOpt.Height) / 2;
bOpt.Location = new Point(header.Width - Theme.D(14) - bOpt.Width, y);
bId.Location = new Point(bOpt.Left - Theme.D(2) - bId.Width, y);
};
body.Dock = DockStyle.Fill; body.AutoScroll = true; body.BackColor = Theme.Bg;
map.HoverChanged += (s, e) => { foreach (var c in cards) { bool h = c.Number == map.Hover; if (c.Highlight != h) { c.Highlight = h; c.Repaint(); } } };
map.ItemDoubleClicked += n => { var c = cards.FirstOrDefault(x => x.Number == n); if (c != null) app.ToggleScreen(c.M, !c.M.Active); };
tips.SetToolTip(map, "Double-clic : allumer / éteindre");
body.Controls.AddRange(new Control[] { secMap, map, secScreens, secProfiles });
body.Resize += (s, e) => Relayout();
footer.Dock = DockStyle.Bottom; footer.Height = Theme.D(28); footer.BackColor = Theme.Bg;
footer.Paint += PaintFooter;
Controls.Add(body); Controls.Add(footer); Controls.Add(header);
BuildOptionsMenu();
itemMenu.Closed += (s, e) => BeginInvoke((Action)(() => Menus.Clear(itemMenu)));
app.Changed += Render;
Activated += (s, e) => app.RefreshIfStale();
Render();
FitHeight();
}
protected override void OnHandleCreated(EventArgs e) { base.OnHandleCreated(e); Win.Style(Handle, Theme.Bg); }
protected override void OnFormClosing(FormClosingEventArgs e)
{
if (e.CloseReason == CloseReason.UserClosing && !app.Exiting) app.OnUserClose();
base.OnFormClosing(e);
}
protected override void OnFormClosed(FormClosedEventArgs e)
{
app.Changed -= Render;
optionsMenu.Dispose(); itemMenu.Dispose(); tips.Dispose();
base.OnFormClosed(e);
}
// ------------------------------------------------ dessin
void PaintHeader(object s, PaintEventArgs e)
{
var g = e.Graphics;
int ls = Theme.D(22), y = (header.Height - ls) / 2;
g.DrawImage(LogoArt.Small(ls), Theme.D(18), y, ls, ls);
Theme.Draw(g, Brand.Name, Theme.F(11f, true), new Rectangle(Theme.D(18) + ls + Theme.D(10), 0, Theme.D(300), header.Height), Theme.Text, TextFormatFlags.VerticalCenter);
}
void PaintFooter(object s, PaintEventArgs e)
{
var g = e.Graphics; var f = Theme.F(8.5f, false);
int pad = Theme.D(18), w = footer.Width - 2 * pad;
string left = app.Busy ? app.Status : (string.IsNullOrEmpty(app.Status) ? app.Summary : app.Status);
Theme.Draw(g, left, f, new Rectangle(pad, 0, w - Theme.D(130), footer.Height), app.StatusError ? Theme.Danger : Theme.Faint, TextFormatFlags.VerticalCenter | TextFormatFlags.EndEllipsis);
Theme.Draw(g, Brand.By, f, new Rectangle(pad, 0, w, footer.Height), Theme.Faint, TextFormatFlags.VerticalCenter | TextFormatFlags.Right);
}
// ------------------------------------------------ synchronisation avec l'etat
void Render()
{
if (IsDisposed) return;
var mons = app.Mons;
UseWaitCursor = app.Busy;
// lignes d'ecrans : recreees seulement si les ecrans branches changent
if (string.Join("|", mons.Select(m => m.DevicePath)) != string.Join("|", cards.Select(c => c.M.DevicePath)))
{
foreach (var c in cards) { body.Controls.Remove(c); c.Dispose(); }
cards.Clear();
foreach (var m0 in mons)
{
var card = new MonitorCard();
card.TgOn.Toggled += (s, e) => app.ToggleScreen(card.M, card.TgOn.Checked);
card.TgHdr.Toggled += (s, e) => app.SetHdr(card.M, card.TgHdr.Checked);
card.HoverChanged += (s, e) => map.SetHover(card.IsHover ? card.Number : -1);
card.RenameRequested += (s, e) => app.RenameScreen(card.M);
card.MenuRequested += pt => ShowScreenMenu(card, pt);
cards.Add(card); body.Controls.Add(card);
}
}
var items = new List<LayoutMap.Item>();
for (int i = 0; i < mons.Count; i++)
{
var m = mons[i];
cards[i].SetData(m, i + 1, TrayApp.Detail(m));
Rectangle r; int hz;
if (Settings.ShowMap && LnkScreenManager.Layout.Bounds(m, out r, out hz)) items.Add(new LayoutMap.Item { M = m, Number = i + 1, R = r });
}
if (Settings.ShowMap) map.SetItems(items);
// profils : reconstruits seulement si la liste ou le profil actif change
string sig = string.Join("|", app.ProfileList.Select(p => p.Name + (app.Matches(p) ? "*" : "")));
if (sig != pillsSig)
{
pillsSig = sig;
foreach (var p in pills) { body.Controls.Remove(p); p.Dispose(); }
pills.Clear();
foreach (var p0 in app.ProfileList)
{
var p = p0;
var pill = new Pill(p.Name) { Active = app.Matches(p) };
pill.MouseUp += (s, e) =>
{
if (e.Button == MouseButtons.Left) app.ApplyProfile(p);
else if (e.Button == MouseButtons.Right) ShowProfileMenu(pill, p, e.Location);
};
tips.SetToolTip(pill, "Clic : appliquer · clic droit : options");
pills.Add(pill); body.Controls.Add(pill);
}
var add = new Pill("+ Nouveau") { Dashed = true };
add.Click += (s, e) => app.NewProfile();
tips.SetToolTip(add, "Enregistrer l'état actuel des écrans comme profil");
pills.Add(add); body.Controls.Add(add);
}
footer.Invalidate();
Relayout();
}
void Relayout()
{
int pad = Theme.D(18), w = body.ClientSize.Width - pad * 2, y = Theme.D(8), sy = body.AutoScrollPosition.Y;
body.SuspendLayout();
secMap.Visible = map.Visible = Settings.ShowMap;
if (Settings.ShowMap)
{
secMap.SetBounds(pad, y + sy, w, secMap.Height); y += secMap.Height + Theme.D(2);
map.SetBounds(pad, y + sy, w, map.Height); y += map.Height + Theme.D(16);
}
secScreens.SetBounds(pad, y + sy, w, secScreens.Height); y += secScreens.Height + Theme.D(2);
foreach (var c in cards) { c.SetBounds(pad, y + sy, w, c.Height); y += c.Height + Theme.D(6); }
y += Theme.D(10);
secProfiles.SetBounds(pad, y + sy, w, secProfiles.Height); y += secProfiles.Height + Theme.D(4);
int x = pad, gap = Theme.D(8);
foreach (var p in pills)
{
if (x > pad && x + p.Width > pad + w) { x = pad; y += p.Height + gap; }
p.Location = new Point(x, y + sy); x += p.Width + gap;
}
if (pills.Count > 0) y += pills[0].Height;
y += Theme.D(14);
body.AutoScrollMinSize = new Size(0, y);
body.ResumeLayout();
}
/// La fenetre prend la hauteur exacte de son contenu (plafonnee a l'ecran).
void FitHeight()
{
Relayout();
int h = header.Height + footer.Height + body.AutoScrollMinSize.Height;
ClientSize = new Size(ClientSize.Width, Math.Min(h, Screen.FromControl(this).WorkingArea.Height - Theme.D(80)));
}
// ------------------------------------------------ menus
void ShowScreenMenu(MonitorCard card, Point pt)
{
var m = card.M;
Menus.Clear(itemMenu);
itemMenu.Items.Add(Menus.Header(m.Model));
itemMenu.Items.Add(Menus.Item("Renommer…", (s, e) => app.RenameScreen(m)));
if (m.HasCustomName) itemMenu.Items.Add(Menus.Item("Reprendre le nom d'origine", (s, e) => app.ResetScreenName(m)));
itemMenu.Items.Add(new ToolStripSeparator());
itemMenu.Items.Add(Menus.Item(m.Active ? "Éteindre" : "Allumer", (s, e) => app.ToggleScreen(m, !m.Active)));
if (m.Active && m.HdrSupported) itemMenu.Items.Add(Menus.Item(m.HdrOn ? "Couper le HDR" : "Activer le HDR", (s, e) => app.SetHdr(m, !m.HdrOn)));
if (m.Active) itemMenu.Items.Add(Menus.Item("Identifier", (s, e) => app.Identify(m)));
itemMenu.Show(card, pt);
}
void ShowProfileMenu(Control anchor, Profile p, Point pt)
{
Menus.Clear(itemMenu);
itemMenu.Items.Add(Menus.Item("Appliquer", (s, e) => app.ApplyProfile(p)));
itemMenu.Items.Add(Menus.Item("Remplacer par l'état actuel", (s, e) => app.ReplaceProfile(p)));
itemMenu.Items.Add(Menus.Item("Raccourci sur le bureau", (s, e) => app.MakeShortcut(p.Name)));
itemMenu.Items.Add(Menus.Item("Renommer…", (s, e) => app.RenameProfile(p)));
itemMenu.Items.Add(new ToolStripSeparator());
var del = Menus.Item("Supprimer", (s, e) => app.DeleteProfile(p)); del.ForeColor = Theme.Danger;
itemMenu.Items.Add(del);
itemMenu.Show(anchor, pt);
}
void BuildOptionsMenu()
{
var tray1 = Menus.Item("Réduire près de l'heure à la fermeture", (s, e) => Settings.TrayOnClose = !Settings.TrayOnClose);
var mapItem = Menus.Item("Afficher la disposition", (s, e) => { Settings.ShowMap = !Settings.ShowMap; Render(); FitHeight(); });
var notif = Menus.Item("Notifications", (s, e) => Settings.NotifyChanges = !Settings.NotifyChanges);
var boot = Menus.Item("Lancer au démarrage de Windows", (s, e) =>
{
try { Startup.Enabled = !Startup.Enabled; app.SetStatus(Startup.Enabled ? "Lancement au démarrage activé." : "Lancement au démarrage désactivé.", false); }
catch (Exception ex) { app.SetStatus("Impossible : " + ex.Message, true); }
});
optionsMenu.Items.AddRange(new ToolStripItem[] { tray1, mapItem, notif, boot, new ToolStripSeparator() });
optionsMenu.Items.Add(Menus.Item("Tout allumer", (s, e) => app.AllOn()));
optionsMenu.Items.Add(Menus.Item("Couper le HDR partout", (s, e) => app.AllHdrOff()));
optionsMenu.Items.Add(Menus.Item("Ouvrir le dossier des données", (s, e) => { try { System.Diagnostics.Process.Start("explorer.exe", "\"" + AppData.Dir + "\""); } catch { } }));
optionsMenu.Items.Add(new ToolStripSeparator());
optionsMenu.Items.Add(Menus.Item("À propos", (s, e) => Dialogs.About(this)));
optionsMenu.Items.Add(Menus.Item("Quitter", (s, e) => app.Exit()));
optionsMenu.Opening += (s, e) => { tray1.Checked = Settings.TrayOnClose; mapItem.Checked = Settings.ShowMap; notif.Checked = Settings.NotifyChanges; boot.Checked = Startup.Enabled; };
}
}
// ------------------------------------------------------------------ Point d'entree
static class Program
{
const string ShowEvent = "LNKScreenManager.Show", RefreshEvent = "LNKScreenManager.Refresh";
[STAThread]
static int Main(string[] args)
{
Win.SetProcessDPIAware();
using (var g = Graphics.FromHwnd(IntPtr.Zero)) Theme.S = g.DpiX / 96f;
string a0 = args.Length > 0 ? args[0].ToLowerInvariant() : "";
try
{
if (a0 == "--make-icon")
{
string dir = args.Length > 1 ? args[1] : ".";
Directory.CreateDirectory(dir);
LogoArt.SaveIco(Path.Combine(dir, "app.ico"));
using (var b = LogoArt.Render(512)) b.Save(Path.Combine(dir, "logo.png"), ImageFormat.Png);
return 0;
}
if (a0 == "--profile" && args.Length >= 2)
{
var p = Profiles.Load().FirstOrDefault(x => string.Equals(x.Name, args[1], StringComparison.OrdinalIgnoreCase));
if (p == null) { MessageBox.Show("Profil introuvable : " + args[1], Brand.Name); return 1; }
Profiles.Apply(p); Signal(RefreshEvent); return 0;
}
if (a0 == "--all-on") { Displays.AllOn(); Signal(RefreshEvent); return 0; }
if (a0 == "--list")
{
Console.WriteLine(string.Join("\n", Displays.List().Select(m => m.Label + " " + m.Hz + " Hz HDR " + (m.HdrSupported ? (m.HdrOn ? "ON" : "off") : "n/a"))));
return 0;
}
}
catch (Exception ex) { MessageBox.Show(ex.Message, Brand.Name, MessageBoxButtons.OK, MessageBoxIcon.Warning); return 1; }
// une seule instance : relancer l'exe rouvre la fenetre de l'instance deja lancee
bool created;
using (var mutex = new Mutex(true, "LNKScreenManager.SingleInstance", out created))
{
if (!created) { Signal(ShowEvent); return 0; }
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Startup.RefreshPath();
using (var app = new TrayApp(a0 == "--tray"))
using (var evShow = new EventWaitHandle(false, EventResetMode.AutoReset, ShowEvent))
using (var evRefresh = new EventWaitHandle(false, EventResetMode.AutoReset, RefreshEvent))
{
// thread endormi en permanence (0 % CPU) : se reveille seulement sur signal d'une autre instance
new Thread(() =>
{
var hs = new WaitHandle[] { evShow, evRefresh };
while (true)
{
int i;
try { i = WaitHandle.WaitAny(hs); } catch { return; }
if (i == 0) app.Post(app.ShowMain); else app.Post(app.RefreshIfOpen);
}
}) { IsBackground = true }.Start();
Application.Run(app);
}
}
return 0;
}
static void Signal(string name)
{
try { using (var ev = EventWaitHandle.OpenExisting(name)) ev.Set(); } catch { }
}
}
}
+513
View File
@@ -0,0 +1,513 @@
// LNK Screen Manager - coeur : ecrans (API Windows CCD), HDR, disposition memorisee, profils.
// By LNK Co (c) 2026
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
namespace LnkScreenManager
{
// ------------------------------------------------------------------ Win32 CCD API
[StructLayout(LayoutKind.Sequential)]
public struct LUID { public uint LowPart; public int HighPart;
public bool Same(LUID o) { return LowPart == o.LowPart && HighPart == o.HighPart; } }
[StructLayout(LayoutKind.Sequential)]
public struct PATH_SOURCE_INFO { public LUID adapterId; public uint id; public uint modeInfoIdx; public uint statusFlags; }
[StructLayout(LayoutKind.Sequential)]
public struct PATH_TARGET_INFO {
public LUID adapterId; public uint id; public uint modeInfoIdx; public uint outputTechnology;
public uint rotation; public uint scaling; public uint refreshNum; public uint refreshDen;
public uint scanLineOrdering; public int targetAvailable; public uint statusFlags; }
[StructLayout(LayoutKind.Sequential)]
public struct PATH_INFO { public PATH_SOURCE_INFO sourceInfo; public PATH_TARGET_INFO targetInfo; public uint flags; }
[StructLayout(LayoutKind.Explicit, Size = 64)]
public struct MODE_INFO {
[FieldOffset(0)] public uint infoType; // 1 = source, 2 = target, 3 = desktop image
[FieldOffset(4)] public uint id;
[FieldOffset(8)] public LUID adapterId;
[FieldOffset(16)] public uint srcWidth;
[FieldOffset(20)] public uint srcHeight;
[FieldOffset(24)] public uint srcPixelFormat;
[FieldOffset(28)] public int srcX;
[FieldOffset(32)] public int srcY;
[FieldOffset(36)] public uint r5; [FieldOffset(40)] public uint r6; [FieldOffset(44)] public uint r7;
[FieldOffset(48)] public uint r8; [FieldOffset(52)] public uint r9; [FieldOffset(56)] public uint r10;
[FieldOffset(60)] public uint r11;
}
[StructLayout(LayoutKind.Sequential)]
public struct DEVICE_INFO_HEADER { public uint type; public uint size; public LUID adapterId; public uint id; }
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct TARGET_DEVICE_NAME {
public DEVICE_INFO_HEADER header; public uint flags; public uint outputTechnology;
public ushort edidManufactureId; public ushort edidProductCodeId; public uint connectorInstance;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 64)] public string monitorFriendlyDeviceName;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)] public string monitorDevicePath; }
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct SOURCE_DEVICE_NAME {
public DEVICE_INFO_HEADER header;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)] public string viewGdiDeviceName; }
[StructLayout(LayoutKind.Sequential)]
public struct ADVANCED_COLOR_INFO { public DEVICE_INFO_HEADER header; public uint value; public uint colorEncoding; public uint bitsPerColorChannel; }
[StructLayout(LayoutKind.Sequential)]
public struct ADVANCED_COLOR_INFO_2 { public DEVICE_INFO_HEADER header; public uint value; public uint colorEncoding; public uint bitsPerColorChannel; public uint activeColorMode; }
[StructLayout(LayoutKind.Sequential)]
public struct SET_VALUE { public DEVICE_INFO_HEADER header; public uint value; }
public static class Native
{
public const uint QDC_ALL_PATHS = 0x1, QDC_ONLY_ACTIVE_PATHS = 0x2;
public const uint SDC_TOPOLOGY_EXTEND = 0x4, SDC_USE_SUPPLIED_DISPLAY_CONFIG = 0x20,
SDC_APPLY = 0x80, SDC_SAVE_TO_DATABASE = 0x200, SDC_ALLOW_CHANGES = 0x400;
public const uint PATH_ACTIVE = 0x1, MODE_IDX_INVALID = 0xffffffff;
[DllImport("user32.dll")] public static extern int GetDisplayConfigBufferSizes(uint flags, out uint numPaths, out uint numModes);
[DllImport("user32.dll")] public static extern int QueryDisplayConfig(uint flags, ref uint numPaths, [Out] PATH_INFO[] paths, ref uint numModes, [Out] MODE_INFO[] modes, IntPtr topologyId);
[DllImport("user32.dll")] public static extern int SetDisplayConfig(uint numPaths, [In] PATH_INFO[] paths, uint numModes, [In] MODE_INFO[] modes, uint flags);
[DllImport("user32.dll")] public static extern int DisplayConfigGetDeviceInfo(ref TARGET_DEVICE_NAME r);
[DllImport("user32.dll")] public static extern int DisplayConfigGetDeviceInfo(ref SOURCE_DEVICE_NAME r);
[DllImport("user32.dll")] public static extern int DisplayConfigGetDeviceInfo(ref ADVANCED_COLOR_INFO r);
[DllImport("user32.dll")] public static extern int DisplayConfigGetDeviceInfo(ref ADVANCED_COLOR_INFO_2 r);
[DllImport("user32.dll")] public static extern int DisplayConfigSetDeviceInfo(ref SET_VALUE r);
public static void Query(uint flags, out PATH_INFO[] paths, out MODE_INFO[] modes)
{
for (int attempt = 0; ; attempt++)
{
uint np, nm;
int err = GetDisplayConfigBufferSizes(flags, out np, out nm);
if (err != 0) throw new Exception("GetDisplayConfigBufferSizes: erreur " + err);
paths = new PATH_INFO[np]; modes = new MODE_INFO[nm];
err = QueryDisplayConfig(flags, ref np, paths, ref nm, modes, IntPtr.Zero);
if (err == 122 && attempt < 5) continue; // ERROR_INSUFFICIENT_BUFFER : la config a change entre-temps
if (err != 0) throw new Exception("QueryDisplayConfig: erreur " + err);
Array.Resize(ref paths, (int)np); Array.Resize(ref modes, (int)nm);
return;
}
}
}
// ------------------------------------------------------------------ Modele
public class Monitor
{
public string Name, DevicePath, GdiName;
public string Model; // nom d origine (modele), Name = nom personnalise s il existe
public bool HasCustomName { get { return Model != null && Model != Name; } }
public LUID AdapterId; public uint TargetId;
public bool Active, Primary;
public int X, Y, Width, Height;
public bool HdrSupported, HdrOn;
public int Hz;
public bool HasModes; public MODE_INFO SrcMode, TgtMode; public PATH_INFO Path;
public string Label { get {
string s = Name;
if (Active) s += " " + Width + "x" + Height + " @ (" + X + "," + Y + ")" + (Primary ? " [principal]" : "");
else s += " (éteint)";
return s; } }
}
public static class Displays
{
static bool hdr2Api = true; // API Windows 11 24H2+ (HDR distinct de l'ACM), avec repli sur l'ancienne
public static List<Monitor> List()
{
PATH_INFO[] paths; MODE_INFO[] modes;
Native.Query(Native.QDC_ALL_PATHS, out paths, out modes);
var result = new List<Monitor>();
// un chemin actif d'abord, puis les inactifs : on garde un seul chemin par ecran
foreach (var p in paths.OrderByDescending(pp => (pp.flags & Native.PATH_ACTIVE) != 0))
{
if (p.targetInfo.targetAvailable == 0) continue;
if (result.Any(x => x.AdapterId.Same(p.targetInfo.adapterId) && x.TargetId == p.targetInfo.id)) continue;
var tn = new TARGET_DEVICE_NAME();
tn.header.type = 2; tn.header.size = (uint)Marshal.SizeOf(tn);
tn.header.adapterId = p.targetInfo.adapterId; tn.header.id = p.targetInfo.id;
if (Native.DisplayConfigGetDeviceInfo(ref tn) != 0) continue;
if (string.IsNullOrEmpty(tn.monitorDevicePath)) continue;
var m = new Monitor {
Name = string.IsNullOrEmpty(tn.monitorFriendlyDeviceName) ? "Écran inconnu" : tn.monitorFriendlyDeviceName,
DevicePath = tn.monitorDevicePath, AdapterId = p.targetInfo.adapterId, TargetId = p.targetInfo.id,
Active = (p.flags & Native.PATH_ACTIVE) != 0 };
if (m.Active)
{
var sn = new SOURCE_DEVICE_NAME();
sn.header.type = 1; sn.header.size = (uint)Marshal.SizeOf(sn);
sn.header.adapterId = p.sourceInfo.adapterId; sn.header.id = p.sourceInfo.id;
if (Native.DisplayConfigGetDeviceInfo(ref sn) == 0) m.GdiName = sn.viewGdiDeviceName;
uint mi = p.sourceInfo.modeInfoIdx;
if (mi != Native.MODE_IDX_INVALID && mi < modes.Length && modes[mi].infoType == 1)
{
m.X = modes[mi].srcX; m.Y = modes[mi].srcY;
m.Width = (int)modes[mi].srcWidth; m.Height = (int)modes[mi].srcHeight;
m.Primary = m.X == 0 && m.Y == 0;
uint ti = p.targetInfo.modeInfoIdx;
if (ti != Native.MODE_IDX_INVALID && ti < modes.Length && modes[ti].infoType == 2)
{ m.HasModes = true; m.SrcMode = modes[mi]; m.TgtMode = modes[ti]; m.Path = p; m.Hz = Layout.HzOf(modes[ti]); }
}
ReadHdr(m);
}
result.Add(m);
}
// nom unique quand deux ecrans identiques (ex. 2x CQ27G2S)
foreach (var g in result.GroupBy(m => m.Name).Where(g => g.Count() > 1))
{
int i = 1;
foreach (var m in g.OrderBy(m => Layout.SortX(m)).ThenBy(m => m.DevicePath)) m.Name += " #" + (i++);
}
foreach (var m in result) { m.Model = m.Name; string cn; if (Names.TryGet(m.DevicePath, out cn)) m.Name = cn; }
Layout.Remember(result);
return result.OrderBy(m => m.Active ? 0 : 1).ThenBy(m => m.X).ThenBy(m => m.Y).ToList();
}
static void ReadHdr(Monitor m)
{
if (hdr2Api)
{
var i2 = new ADVANCED_COLOR_INFO_2();
i2.header.type = 15; i2.header.size = (uint)Marshal.SizeOf(i2);
i2.header.adapterId = m.AdapterId; i2.header.id = m.TargetId;
if (Native.DisplayConfigGetDeviceInfo(ref i2) == 0)
{
m.HdrSupported = (i2.value & 0x10) != 0; // highDynamicRangeSupported
m.HdrOn = (i2.value & 0x20) != 0; // highDynamicRangeUserEnabled
return;
}
hdr2Api = false;
}
var i = new ADVANCED_COLOR_INFO();
i.header.type = 9; i.header.size = (uint)Marshal.SizeOf(i);
i.header.adapterId = m.AdapterId; i.header.id = m.TargetId;
if (Native.DisplayConfigGetDeviceInfo(ref i) == 0)
{
m.HdrSupported = (i.value & 0x1) != 0;
m.HdrOn = (i.value & 0x2) != 0;
}
}
public static void SetHdr(Monitor m, bool on)
{
var s = new SET_VALUE();
s.header.size = (uint)Marshal.SizeOf(s);
s.header.adapterId = m.AdapterId; s.header.id = m.TargetId; s.value = on ? 1u : 0u;
int err = -1;
if (hdr2Api) { s.header.type = 16; err = Native.DisplayConfigSetDeviceInfo(ref s); } // SET_HDR_STATE
if (err != 0) { s.header.type = 10; err = Native.DisplayConfigSetDeviceInfo(ref s); } // SET_ADVANCED_COLOR_STATE
if (err != 0) throw new Exception("Impossible de changer le HDR de " + m.Name + " (erreur " + err + ")");
}
static string Key(LUID a, uint id) { return a.LowPart + ":" + a.HighPart + ":" + id; }
/// Applique en UNE seule operation l'ensemble des ecrans allumes (les autres sont eteints).
public static void SetActive(ICollection<string> devicePathsOn)
{
if (SetActive(devicePathsOn, true) == 0) return;
int err = SetActive(devicePathsOn, false);
if (err != 0) throw new Exception("Windows a refusé la configuration (erreur " + err + ").");
}
static int SetActive(ICollection<string> devicePathsOn, bool useSaved)
{
if (devicePathsOn.Count == 0) throw new Exception("Il faut garder au moins un écran allumé.");
var mons = List();
var wanted = new HashSet<string>(mons.Where(m => devicePathsOn.Contains(m.DevicePath)).Select(m => Key(m.AdapterId, m.TargetId)));
if (wanted.Count == 0) throw new Exception("Aucun des écrans demandés n'est branché.");
PATH_INFO[] all; MODE_INFO[] modes;
Native.Query(Native.QDC_ALL_PATHS, out all, out modes);
var keep = new List<PATH_INFO>();
var done = new HashSet<string>();
// 1) chemins deja actifs qu'on garde
foreach (var p in all)
{
string k = Key(p.targetInfo.adapterId, p.targetInfo.id);
if ((p.flags & Native.PATH_ACTIVE) != 0 && wanted.Contains(k) && done.Add(k)) keep.Add(p);
}
// 2) ecrans a rallumer : un chemin inactif avec une source libre
bool anyEnabled = false;
var extra = new List<MODE_INFO>();
foreach (var p0 in all)
{
var p = p0;
string k = Key(p.targetInfo.adapterId, p.targetInfo.id);
if (!wanted.Contains(k) || done.Contains(k) || p.targetInfo.targetAvailable == 0) continue;
bool sourceUsed = keep.Any(q => q.sourceInfo.adapterId.Same(p.sourceInfo.adapterId) && q.sourceInfo.id == p.sourceInfo.id);
if (sourceUsed) continue;
p.flags = Native.PATH_ACTIVE;
p.sourceInfo.modeInfoIdx = Native.MODE_IDX_INVALID;
p.targetInfo.modeInfoIdx = Native.MODE_IDX_INVALID;
var mon = mons.FirstOrDefault(x => Key(x.AdapterId, x.TargetId) == k);
Layout.Entry saved;
if (useSaved && mon != null && Layout.TryGet(mon.DevicePath, out saved))
{
var sm = saved.Src; sm.id = p.sourceInfo.id; sm.adapterId = p.sourceInfo.adapterId;
var tm = saved.Tgt; tm.id = p.targetInfo.id; tm.adapterId = p.targetInfo.adapterId;
p.sourceInfo.modeInfoIdx = (uint)(modes.Length + extra.Count); extra.Add(sm);
p.targetInfo.modeInfoIdx = (uint)(modes.Length + extra.Count); extra.Add(tm);
p.targetInfo.refreshNum = saved.Path.targetInfo.refreshNum; p.targetInfo.refreshDen = saved.Path.targetInfo.refreshDen;
p.targetInfo.rotation = saved.Path.targetInfo.rotation; p.targetInfo.scaling = saved.Path.targetInfo.scaling;
p.targetInfo.scanLineOrdering = saved.Path.targetInfo.scanLineOrdering;
}
keep.Add(p); done.Add(k); anyEnabled = true;
}
if (extra.Count > 0) modes = modes.Concat(extra).ToArray();
// 3) on ne garde que les modes references, re-indexes
var newModes = new List<MODE_INFO>();
var map = new Dictionary<uint, uint>();
Func<uint, uint> remap = idx => {
if (idx == Native.MODE_IDX_INVALID || idx >= modes.Length) return Native.MODE_IDX_INVALID;
uint n; if (!map.TryGetValue(idx, out n)) { n = (uint)newModes.Count; newModes.Add(modes[idx]); map[idx] = n; }
return n; };
var arr = keep.ToArray();
for (int i = 0; i < arr.Length; i++)
{
arr[i].sourceInfo.modeInfoIdx = remap(arr[i].sourceInfo.modeInfoIdx);
arr[i].targetInfo.modeInfoIdx = remap(arr[i].targetInfo.modeInfoIdx);
}
var mArr = newModes.ToArray();
if (anyEnabled && useSaved)
for (int i = 0; i < arr.Length; i++)
{
var mon2 = mons.FirstOrDefault(x => x.AdapterId.Same(arr[i].targetInfo.adapterId) && x.TargetId == arr[i].targetInfo.id);
Layout.Entry saved2; uint si = arr[i].sourceInfo.modeInfoIdx;
if (mon2 != null && si < mArr.Length && Layout.TryGet(mon2.DevicePath, out saved2)) { mArr[si].srcX = saved2.Src.srcX; mArr[si].srcY = saved2.Src.srcY; }
}
// 4) si l'ecran principal (0,0) disparait, on decale le bureau pour qu'un ecran restant devienne principal
var srcIdx = Enumerable.Range(0, mArr.Length).Where(i => mArr[i].infoType == 1).ToList();
if (srcIdx.Count > 0 && !srcIdx.Any(i => mArr[i].srcX == 0 && mArr[i].srcY == 0))
{
int b = srcIdx.OrderBy(i => Math.Abs(mArr[i].srcX) + Math.Abs(mArr[i].srcY)).First();
int dx = mArr[b].srcX, dy = mArr[b].srcY;
foreach (int i in srcIdx) { mArr[i].srcX -= dx; mArr[i].srcY -= dy; }
}
uint flags = Native.SDC_APPLY | Native.SDC_USE_SUPPLIED_DISPLAY_CONFIG | Native.SDC_ALLOW_CHANGES | Native.SDC_SAVE_TO_DATABASE;
int err = Native.SetDisplayConfig((uint)arr.Length, arr, (uint)mArr.Length, mArr, flags);
if (err != 0 && useSaved) return err;
if (err != 0 && anyEnabled)
{
// repli : tout rallumer (Windows reprend les positions memorisees), puis eteindre ceux en trop
AllOn(); Thread.Sleep(1500);
var still = List().Where(m => m.Active).Select(m => m.DevicePath).ToList();
if (still.Any(d => !devicePathsOn.Contains(d))) return SetActive(devicePathsOn, false);
err = 0;
}
return err;
}
public static void AllOn()
{
int err = Native.SetDisplayConfig(0, null, 0, null, Native.SDC_APPLY | Native.SDC_TOPOLOGY_EXTEND);
if (err != 0) throw new Exception("Impossible de tout rallumer (erreur " + err + ").");
}
public static void WaitFor(Func<List<Monitor>, bool> cond, int ms = 6000)
{
var end = DateTime.Now.AddMilliseconds(ms);
while (DateTime.Now < end) { Thread.Sleep(300); try { if (cond(List())) { Thread.Sleep(500); return; } } catch { } }
}
}
// ------------------------------------------------------------------ Noms personnalises des ecrans (names.txt)
public static class Names
{
static Dictionary<string, string> cache;
static string FilePath { get { return AppData.File("names.txt"); } }
static void Load()
{
if (cache != null) return;
cache = new Dictionary<string, string>();
try
{
if (File.Exists(FilePath))
foreach (var l in File.ReadAllLines(FilePath, Encoding.UTF8))
{
int i = l.IndexOf('|');
if (i > 0 && l.Length > i + 1) cache[l.Substring(0, i)] = l.Substring(i + 1);
}
}
catch { }
}
public static bool TryGet(string devicePath, out string name) { Load(); return cache.TryGetValue(devicePath, out name); }
/// Donne un nom a un ecran ; nom vide = retour au nom d'origine.
public static void Set(string devicePath, string name)
{
Load();
name = (name ?? "").Replace("|", " ").Replace("\r", " ").Replace("\n", " ").Trim();
if (name.Length > 40) name = name.Substring(0, 40);
if (name.Length == 0) cache.Remove(devicePath); else cache[devicePath] = name;
File.WriteAllLines(FilePath, cache.Select(kv => kv.Key + "|" + kv.Value), Encoding.UTF8);
}
}
// ------------------------------------------------------------------ Dossier de donnees (%APPDATA%\LNK Screen Manager)
public static class AppData
{
public static string Dir
{
get
{
string d = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "LNK Screen Manager");
Directory.CreateDirectory(d);
return d;
}
}
/// Chemin d'un fichier de donnees ; reprend automatiquement un ancien fichier pose a cote de l'exe.
public static string File(string name)
{
string p = System.IO.Path.Combine(Dir, name);
if (!System.IO.File.Exists(p))
{
try
{
string old = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(typeof(AppData).Assembly.Location), name);
if (System.IO.File.Exists(old)) System.IO.File.Copy(old, p);
}
catch { }
}
return p;
}
}
// ------------------------------------------------------------------ Disposition memorisee (position, resolution, frequence)
public static class Layout
{
public class Entry { public MODE_INFO Src, Tgt; public PATH_INFO Path; }
static Dictionary<string, Entry> cache;
static string FilePath { get { return AppData.File("layout.txt"); } }
static string Enc<T>(T s) where T : struct { int n = Marshal.SizeOf(typeof(T)); var b = new byte[n]; var h = GCHandle.Alloc(b, GCHandleType.Pinned); Marshal.StructureToPtr(s, h.AddrOfPinnedObject(), false); h.Free(); return Convert.ToBase64String(b); }
static T Dec<T>(string s) where T : struct { var b = Convert.FromBase64String(s); var h = GCHandle.Alloc(b, GCHandleType.Pinned); var r = (T)Marshal.PtrToStructure(h.AddrOfPinnedObject(), typeof(T)); h.Free(); return r; }
static void Load()
{
if (cache != null) return;
cache = new Dictionary<string, Entry>();
try { if (File.Exists(FilePath)) foreach (var l in File.ReadAllLines(FilePath)) { var p = l.Split('|'); if (p.Length == 4) cache[p[0]] = new Entry { Src = Dec<MODE_INFO>(p[1]), Tgt = Dec<MODE_INFO>(p[2]), Path = Dec<PATH_INFO>(p[3]) }; } } catch { }
}
public static bool TryGet(string devicePath, out Entry e) { Load(); return cache.TryGetValue(devicePath, out e); }
// comparaison directe des 64 octets utiles du mode (sans allocation)
static bool Same(MODE_INFO a, MODE_INFO b)
{
return a.infoType == b.infoType && a.srcWidth == b.srcWidth && a.srcHeight == b.srcHeight && a.srcPixelFormat == b.srcPixelFormat
&& a.srcX == b.srcX && a.srcY == b.srcY && a.r5 == b.r5 && a.r6 == b.r6 && a.r7 == b.r7
&& a.r8 == b.r8 && a.r9 == b.r9 && a.r10 == b.r10 && a.r11 == b.r11;
}
// Frequence (Hz) d'un mode cible : vSyncFreq = offsets 32/36 de l'union DISPLAYCONFIG_VIDEO_SIGNAL_INFO
public static int HzOf(MODE_INFO t)
{
uint num = (uint)t.srcY, den = t.r5;
return den == 0 ? 0 : (int)Math.Round((double)num / den);
}
public static int SortX(Monitor m) { Entry e; return TryGet(m.DevicePath, out e) ? e.Src.srcX : m.X; }
/// Rectangle de bureau (memorise si l'ecran est eteint) + infos d'affichage.
public static bool Bounds(Monitor m, out Rectangle r, out int hz)
{
Entry e;
if (TryGet(m.DevicePath, out e)) { r = new Rectangle(e.Src.srcX, e.Src.srcY, (int)e.Src.srcWidth, (int)e.Src.srcHeight); hz = HzOf(e.Tgt); if (!m.Active) return true; }
else { r = Rectangle.Empty; hz = 0; }
if (m.Active) { r = new Rectangle(m.X, m.Y, m.Width, m.Height); hz = m.Hz; return true; }
return false;
}
// Memorise la disposition quand tous les ecrans sont allumes (= disposition "normale"), ou la 1re fois qu'on voit un ecran.
public static void Remember(List<Monitor> mons)
{
Load();
bool allOn = mons.All(m => m.Active);
bool changed = false;
foreach (var m in mons.Where(m => m.HasModes && (allOn || !cache.ContainsKey(m.DevicePath))))
{
var e = new Entry { Src = m.SrcMode, Tgt = m.TgtMode, Path = m.Path };
Entry old;
if (!cache.TryGetValue(m.DevicePath, out old) || !Same(old.Src, e.Src) || !Same(old.Tgt, e.Tgt)) { cache[m.DevicePath] = e; changed = true; }
}
if (changed) try { File.WriteAllLines(FilePath, cache.Select(kv => kv.Key + "|" + Enc(kv.Value.Src) + "|" + Enc(kv.Value.Tgt) + "|" + Enc(kv.Value.Path))); } catch { }
}
}
// ------------------------------------------------------------------ Profils (fichier texte a cote de l'exe)
public class Profile { public string Name; public Dictionary<string, bool[]> Screens = new Dictionary<string, bool[]>(); } // [allume, hdr]
public static class Profiles
{
public static string FilePath { get { return AppData.File("profiles.txt"); } }
public static List<Profile> Load()
{
var list = new List<Profile>();
if (!File.Exists(FilePath)) return list;
foreach (var line in File.ReadAllLines(FilePath, Encoding.UTF8))
{
var parts = line.Split('|');
if (parts.Length < 2 || parts[0].Trim() == "" || parts[0].StartsWith("#")) continue;
var p = new Profile { Name = parts[0].Trim() };
foreach (var s in parts[1].Split(';'))
{
int eq = s.LastIndexOf('='); if (eq < 0) continue;
var v = s.Substring(eq + 1).Split(',');
p.Screens[s.Substring(0, eq)] = new[] { v[0] == "1", v.Length > 1 && v[1] == "1" };
}
list.Add(p);
}
return list;
}
public static void Save(List<Profile> list)
{
File.WriteAllLines(FilePath, list.Select(p => p.Name + "|" + string.Join(";",
p.Screens.Select(kv => kv.Key + "=" + (kv.Value[0] ? "1" : "0") + "," + (kv.Value[1] ? "1" : "0")))), Encoding.UTF8);
}
public static Profile FromCurrent(string name)
{
var p = new Profile { Name = name };
foreach (var m in Displays.List()) p.Screens[m.DevicePath] = new[] { m.Active, m.HdrOn };
return p;
}
public static void Apply(Profile p)
{
var on = p.Screens.Where(kv => kv.Value[0]).Select(kv => kv.Key).ToList();
var current = Displays.List();
var currentOn = current.Where(m => m.Active).Select(m => m.DevicePath).ToList();
bool topoChange = !(new HashSet<string>(currentOn).SetEquals(on.Where(d => current.Any(m => m.DevicePath == d))));
if (topoChange)
{
Displays.SetActive(on);
Displays.WaitFor(l => on.Where(d => l.Any(m => m.DevicePath == d)).All(d => l.Any(m => m.DevicePath == d && m.Active)));
}
foreach (var m in Displays.List().Where(m => m.Active && m.HdrSupported))
{
bool[] v;
if (p.Screens.TryGetValue(m.DevicePath, out v) && v[1] != m.HdrOn) Displays.SetHdr(m, v[1]);
}
}
}
}
+658
View File
@@ -0,0 +1,658 @@
// LNK Screen Manager - theme sobre, logo et controles.
// By LNK Co (c) 2026
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Drawing.Text;
using System.IO;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace LnkScreenManager
{
static class Brand
{
public const string Name = "LNK Screen Manager";
public const string By = "By LNK Co © 2026";
public const string Version = "1.1";
}
// ------------------------------------------------------------------ Theme (plat, une seule couleur d'accent)
static class Theme
{
public static float S = 1f;
public static int D(float px) { return (int)Math.Round(px * S); }
public static readonly Color
Bg = Color.FromArgb(17, 19, 23), Card = Color.FromArgb(25, 28, 33), CardHover = Color.FromArgb(32, 36, 42),
Border = Color.FromArgb(44, 48, 56), Text = Color.FromArgb(232, 234, 237), Dim = Color.FromArgb(154, 160, 166),
Faint = Color.FromArgb(98, 103, 110), Accent = Color.FromArgb(79, 140, 255), Danger = Color.FromArgb(242, 110, 110),
Brand1 = Color.FromArgb(124, 92, 255), Brand2 = Color.FromArgb(34, 193, 238); // logo uniquement
static string iconFamily;
public static string IconFamily
{
get
{
if (iconFamily == null)
using (var f = new Font("Segoe Fluent Icons", 10f)) iconFamily = f.Name == "Segoe Fluent Icons" ? f.Name : "Segoe MDL2 Assets";
return iconFamily;
}
}
static readonly Dictionary<string, Font> fonts = new Dictionary<string, Font>();
public static Font F(float pt, bool semibold) { return Face(semibold ? "Segoe UI Semibold" : "Segoe UI", pt); }
public static Font IconF(float pt) { return Face(IconFamily, pt); }
public static Font Face(string family, float pt)
{
string k = family + "|" + pt; Font f;
if (!fonts.TryGetValue(k, out f)) { f = new Font(family, pt, FontStyle.Regular, GraphicsUnit.Point); fonts[k] = f; }
return f;
}
public static GraphicsPath Round(RectangleF r, float rad)
{
var p = new GraphicsPath();
float d = Math.Min(rad * 2, Math.Min(r.Width, r.Height));
if (d <= 0.5f) { p.AddRectangle(r); return p; }
p.AddArc(r.X, r.Y, d, d, 180, 90);
p.AddArc(r.Right - d, r.Y, d, d, 270, 90);
p.AddArc(r.Right - d, r.Bottom - d, d, d, 0, 90);
p.AddArc(r.X, r.Bottom - d, d, d, 90, 90);
p.CloseFigure();
return p;
}
public static void Fill(Graphics g, RectangleF r, float rad, Color c) { using (var p = Round(r, rad)) using (var b = new SolidBrush(c)) g.FillPath(b, p); }
public static void Stroke(Graphics g, RectangleF r, float rad, Color c, float w, bool dash)
{
using (var p = Round(r, rad)) using (var pen = new Pen(c, w)) { if (dash) pen.DashStyle = DashStyle.Dash; g.DrawPath(pen, p); }
}
public static void HQ(Graphics g)
{
g.SmoothingMode = SmoothingMode.AntiAlias;
g.PixelOffsetMode = PixelOffsetMode.HighQuality;
}
public static void Draw(Graphics g, string s, Font f, Rectangle r, Color c, TextFormatFlags flags)
{
TextRenderer.DrawText(g, s, f, r, c, flags | TextFormatFlags.NoPrefix | TextFormatFlags.NoPadding);
}
public static Size Measure(string s, Font f)
{
return TextRenderer.MeasureText(s, f, new Size(int.MaxValue, int.MaxValue), TextFormatFlags.NoPrefix | TextFormatFlags.NoPadding);
}
public const TextFormatFlags Center = TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter;
}
static class Glyph
{
public const string Settings = "", Identify = "", Check = "", Edit = "";
}
static class Win
{
[DllImport("dwmapi.dll")] static extern int DwmSetWindowAttribute(IntPtr h, int attr, ref int val, int size);
[DllImport("user32.dll")] public static extern bool SetProcessDPIAware();
[DllImport("kernel32.dll")] static extern IntPtr GetCurrentProcess();
[DllImport("kernel32.dll")] static extern bool SetProcessWorkingSetSize(IntPtr p, IntPtr min, IntPtr max);
/// Barre de titre sombre + coins arrondis (Windows 11).
public static void Style(IntPtr h, Color caption)
{
try
{
int on = 1; DwmSetWindowAttribute(h, 20, ref on, 4);
int c = caption.R | (caption.G << 8) | (caption.B << 16); DwmSetWindowAttribute(h, 35, ref c, 4);
int corner = 2; DwmSetWindowAttribute(h, 33, ref corner, 4);
}
catch { }
}
/// Rend la memoire inutilisee a Windows (quand l'appli n'est plus qu'une icone pres de l'heure).
public static void Trim()
{
try
{
GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect();
SetProcessWorkingSetSize(GetCurrentProcess(), (IntPtr)(-1), (IntPtr)(-1));
}
catch { }
}
}
// ------------------------------------------------------------------ Logo (vectoriel ; sert aussi a generer l'icone)
static class LogoArt
{
static readonly Dictionary<int, Bitmap> small = new Dictionary<int, Bitmap>();
public static Bitmap Small(int s) { Bitmap b; if (!small.TryGetValue(s, out b)) { b = Render(s); small[s] = b; } return b; }
public static Bitmap Render(int s)
{
var bmp = new Bitmap(s, s, PixelFormat.Format32bppArgb);
using (var g = Graphics.FromImage(bmp))
{
Theme.HQ(g); g.TextRenderingHint = TextRenderingHint.AntiAliasGridFit; g.InterpolationMode = InterpolationMode.HighQualityBicubic;
Draw(g, new RectangleF(0, 0, s, s));
}
return bmp;
}
public static void Draw(Graphics g, RectangleF r)
{
float s = r.Width;
var bg = RectangleF.Inflate(r, -s * 0.03f, -s * 0.03f);
using (var path = Theme.Round(bg, s * 0.24f))
{
using (var br = new LinearGradientBrush(bg, Theme.Brand1, Theme.Brand2, 45f)) g.FillPath(br, path);
var top = new RectangleF(bg.X, bg.Y, bg.Width, bg.Height * 0.55f);
using (var hl = new LinearGradientBrush(new RectangleF(top.X, top.Y - 1, top.Width, top.Height + 2), Color.FromArgb(55, 255, 255, 255), Color.FromArgb(0, 255, 255, 255), 90f))
{
var old = g.Clip; g.SetClip(path); g.FillRectangle(hl, top); g.Clip = old;
}
}
float sw = Math.Max(1.4f, s * 0.062f);
var scr = new RectangleF(r.X + s * 0.2f, r.Y + s * 0.23f, s * 0.6f, s * 0.41f);
using (var sp = Theme.Round(scr, s * 0.07f))
{
if (s < 30) g.FillPath(Brushes.White, sp);
else
{
using (var fill = new SolidBrush(Color.FromArgb(50, 255, 255, 255))) g.FillPath(fill, sp);
using (var pen = new Pen(Color.White, sw)) g.DrawPath(pen, sp);
}
}
float nx = r.X + s * 0.5f, ty = scr.Bottom + (s < 30 ? 0 : sw * 0.5f);
g.FillRectangle(Brushes.White, nx - s * 0.045f, ty, s * 0.09f, s * 0.085f);
using (var bp = Theme.Round(new RectangleF(nx - s * 0.19f, ty + s * 0.08f, s * 0.38f, s * 0.065f), s * 0.032f)) g.FillPath(Brushes.White, bp);
if (s >= 40)
using (var f = new Font("Segoe UI Black", scr.Height * 0.40f, FontStyle.Regular, GraphicsUnit.Pixel))
using (var sf = new StringFormat { Alignment = StringAlignment.Center, LineAlignment = StringAlignment.Center })
g.DrawString("LNK", f, Brushes.White, new RectangleF(scr.X, scr.Y + scr.Height * 0.04f, scr.Width, scr.Height), sf);
}
public static void SaveIco(string path)
{
int[] sizes = { 16, 20, 24, 32, 40, 48, 64, 128, 256 };
var pngs = new List<byte[]>();
foreach (int sz in sizes)
using (var b = Render(sz)) using (var ms = new MemoryStream()) { b.Save(ms, ImageFormat.Png); pngs.Add(ms.ToArray()); }
using (var fs = File.Create(path)) using (var w = new BinaryWriter(fs))
{
w.Write((short)0); w.Write((short)1); w.Write((short)sizes.Length);
int offset = 6 + 16 * sizes.Length;
for (int i = 0; i < sizes.Length; i++)
{
byte d = (byte)(sizes[i] >= 256 ? 0 : sizes[i]);
w.Write(d); w.Write(d); w.Write((byte)0); w.Write((byte)0);
w.Write((short)1); w.Write((short)32); w.Write(pngs[i].Length); w.Write(offset);
offset += pngs[i].Length;
}
foreach (var p in pngs) w.Write(p);
}
}
/// Icone integree a l'exe (taille choisie), ou dessinee a la volee si absente.
public static Icon AppIcon(int size)
{
try
{
using (var st = typeof(LogoArt).Assembly.GetManifestResourceStream("LnkScreenManager.app.ico"))
if (st != null) return new Icon(st, size, size);
}
catch { }
using (var b = Render(size)) return Icon.FromHandle(b.GetHicon());
}
}
// ------------------------------------------------------------------ Controles (dessines a la main, sans animation)
class Smooth : Control
{
public Smooth()
{
SetStyle(ControlStyles.UserPaint | ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer | ControlStyles.ResizeRedraw, true);
SetStyle(ControlStyles.StandardDoubleClick | ControlStyles.Selectable, false);
TabStop = false;
}
protected Color ParentBg { get { return Parent != null ? Parent.BackColor : Theme.Bg; } }
}
class Toggle : Smooth
{
bool on;
public event EventHandler Toggled;
public Toggle() { Size = new Size(Theme.D(38), Theme.D(20)); Cursor = Cursors.Hand; }
public bool Checked { get { return on; } set { if (on != value) { on = value; Invalidate(); } } }
protected override void OnClick(EventArgs e)
{
base.OnClick(e);
if (!Enabled) return;
on = !on; Invalidate();
if (Toggled != null) Toggled(this, EventArgs.Empty);
}
protected override void OnEnabledChanged(EventArgs e) { base.OnEnabledChanged(e); Cursor = Enabled ? Cursors.Hand : Cursors.Default; Invalidate(); }
protected override void OnPaint(PaintEventArgs e)
{
var g = e.Graphics; Theme.HQ(g); g.Clear(BackColor);
var r = new RectangleF(0.5f, 0.5f, Width - 1.5f, Height - 1.5f);
bool lit = on && Enabled;
if (lit) Theme.Fill(g, r, r.Height / 2, Theme.Accent);
else Theme.Stroke(g, r, r.Height / 2, Enabled ? Theme.Faint : Theme.Border, 1f, false);
float k = r.Height - Theme.D(8), y = r.Y + (r.Height - k) / 2;
float x = lit ? r.Right - Theme.D(4) - k : r.X + Theme.D(4);
using (var b = new SolidBrush(lit ? Color.White : (Enabled ? Theme.Dim : Theme.Border))) g.FillEllipse(b, x, y, k, k);
}
}
class IconButton : Smooth
{
readonly string glyph; bool hover;
public IconButton(string glyph) { this.glyph = glyph; Size = new Size(Theme.D(34), Theme.D(34)); Cursor = Cursors.Hand; }
protected override void OnMouseEnter(EventArgs e) { hover = true; Invalidate(); base.OnMouseEnter(e); }
protected override void OnMouseLeave(EventArgs e) { hover = false; Invalidate(); base.OnMouseLeave(e); }
protected override void OnPaint(PaintEventArgs e)
{
var g = e.Graphics; Theme.HQ(g); g.Clear(ParentBg);
if (hover) Theme.Fill(g, new RectangleF(0, 0, Width, Height), Theme.D(6), Theme.Card);
Theme.Draw(g, glyph, Theme.IconF(11f), ClientRectangle, hover ? Theme.Text : Theme.Dim, Theme.Center);
}
}
/// Bouton texte (profils, dialogues).
class Pill : Smooth
{
bool hover;
public bool Active, Dashed, Primary;
public Pill(string text) { Text = text; Cursor = Cursors.Hand; Fit(); }
public void Fit()
{
int w = Theme.Measure(Text, Theme.F(9.5f, false)).Width + Theme.D(28);
Size = new Size(Math.Max(w, Theme.D(64)), Theme.D(30));
}
protected override void OnMouseEnter(EventArgs e) { hover = true; Invalidate(); base.OnMouseEnter(e); }
protected override void OnMouseLeave(EventArgs e) { hover = false; Invalidate(); base.OnMouseLeave(e); }
protected override void OnPaint(PaintEventArgs e)
{
var g = e.Graphics; Theme.HQ(g); g.Clear(ParentBg);
var r = new RectangleF(0.5f, 0.5f, Width - 1.5f, Height - 1.5f);
float rad = Theme.D(6);
if (Primary) Theme.Fill(g, r, rad, hover ? Color.FromArgb(104, 157, 255) : Theme.Accent);
else if (Dashed) { if (hover) Theme.Fill(g, r, rad, Theme.Card); Theme.Stroke(g, r, rad, Theme.Border, 1f, true); }
else { Theme.Fill(g, r, rad, hover ? Theme.CardHover : Theme.Card); if (Active) Theme.Stroke(g, r, rad, Theme.Accent, 1f, false); }
Color tc = Primary ? Color.White : Active ? Theme.Accent : Dashed ? (hover ? Theme.Text : Theme.Dim) : Theme.Text;
Theme.Draw(g, Text, Theme.F(9.5f, false), ClientRectangle, tc, Theme.Center | TextFormatFlags.EndEllipsis);
}
}
/// Titre de section ; pour la liste des ecrans, affiche aussi les colonnes ECRAN / HDR une seule fois.
class SectionHeader : Smooth
{
public bool Columns;
public SectionHeader(string text) { Text = text.ToUpperInvariant(); Height = Theme.D(26); }
protected override void OnPaint(PaintEventArgs e)
{
var g = e.Graphics; g.Clear(ParentBg);
var f = Theme.F(8f, true);
Theme.Draw(g, Text, f, new Rectangle(0, 0, Width, Height), Theme.Faint, TextFormatFlags.VerticalCenter);
if (!Columns) return;
int tw = Theme.D(38);
Theme.Draw(g, "ÉCRAN", f, new Rectangle(Width - Theme.D(MonitorCard.ColOn) - Theme.D(10), 0, tw + Theme.D(20), Height), Theme.Faint, Theme.Center);
Theme.Draw(g, "HDR", f, new Rectangle(Width - Theme.D(MonitorCard.ColHdr) - Theme.D(10), 0, tw + Theme.D(20), Height), Theme.Faint, Theme.Center);
}
}
/// Ligne d'un ecran : numero, nom, infos, interrupteurs.
class MonitorCard : Smooth
{
public const int ColOn = 124, ColHdr = 58; // distance bord droit -> interrupteur (px a 100 %)
public Monitor M; public int Number; public bool Highlight;
string detail = "", sig;
bool hover;
Rectangle nameZone = Rectangle.Empty;
public readonly Toggle TgOn = new Toggle(), TgHdr = new Toggle();
public event EventHandler HoverChanged, RenameRequested;
public event Action<Point> MenuRequested;
public MonitorCard()
{
Height = Theme.D(54);
Controls.Add(TgOn); Controls.Add(TgHdr);
foreach (var t in new[] { TgOn, TgHdr })
{
t.MouseEnter += (s, e) => SetHover(true);
t.MouseLeave += (s, e) => CheckLeave();
}
}
public bool IsHover { get { return hover; } }
void SetHover(bool v) { if (hover == v) return; hover = v; Repaint(); if (HoverChanged != null) HoverChanged(this, EventArgs.Empty); }
void CheckLeave() { if (!ClientRectangle.Contains(PointToClient(Cursor.Position))) SetHover(false); }
protected override void OnMouseEnter(EventArgs e) { SetHover(true); base.OnMouseEnter(e); }
protected override void OnMouseLeave(EventArgs e) { CheckLeave(); base.OnMouseLeave(e); }
protected override void OnMouseMove(MouseEventArgs e) { base.OnMouseMove(e); Cursor = nameZone.Contains(e.Location) ? Cursors.Hand : Cursors.Default; }
protected override void OnMouseUp(MouseEventArgs e)
{
base.OnMouseUp(e);
if (e.Button == MouseButtons.Left && nameZone.Contains(e.Location) && RenameRequested != null) RenameRequested(this, EventArgs.Empty);
if (e.Button == MouseButtons.Right && MenuRequested != null) MenuRequested(e.Location);
}
public void Repaint()
{
var bg = (hover || Highlight) ? Theme.CardHover : Theme.Card;
TgOn.BackColor = bg; TgHdr.BackColor = bg;
Invalidate(true);
}
/// Met a jour la ligne ; ne redessine que si quelque chose a change.
public void SetData(Monitor m, int number, string det)
{
string s = number + "|" + m.Name + "|" + det + "|" + m.Active + m.Primary + m.HdrSupported + m.HdrOn;
M = m; Number = number; detail = det;
TgOn.Checked = m.Active;
TgHdr.Checked = m.Active && m.HdrOn;
TgHdr.Enabled = m.Active && m.HdrSupported;
TgHdr.Visible = !(m.Active && !m.HdrSupported);
if (s != sig) { sig = s; Invalidate(); }
}
protected override void OnLayout(LayoutEventArgs e)
{
base.OnLayout(e);
int y = (Height - TgOn.Height) / 2;
TgOn.Location = new Point(Width - Theme.D(ColOn), y);
TgHdr.Location = new Point(Width - Theme.D(ColHdr), y);
}
protected override void OnPaint(PaintEventArgs e)
{
if (M == null) return;
var g = e.Graphics; Theme.HQ(g); g.Clear(ParentBg);
bool hl = hover || Highlight;
Theme.Fill(g, new RectangleF(0, 0, Width, Height), Theme.D(8), hl ? Theme.CardHover : Theme.Card);
if (Highlight) Theme.Stroke(g, new RectangleF(0.5f, 0.5f, Width - 1.5f, Height - 1.5f), Theme.D(8), Theme.Accent, 1f, false);
Theme.Draw(g, Number.ToString(), Theme.F(10f, true), new Rectangle(Theme.D(8), 0, Theme.D(26), Height), M.Active ? Theme.Dim : Theme.Faint, Theme.Center);
int x = Theme.D(42), maxRight = Width - Theme.D(ColOn) - Theme.D(14);
var nf = Theme.F(10.5f, true);
var ns = Theme.Measure(M.Name, nf);
int penW = Theme.D(22);
int nameW = Math.Max(0, Math.Min(ns.Width, maxRight - x - penW));
int ny = Theme.D(8);
Theme.Draw(g, M.Name, nf, new Rectangle(x, ny, nameW + 2, ns.Height + 2), M.Active ? Theme.Text : Theme.Dim, TextFormatFlags.EndEllipsis);
var penRect = new Rectangle(x + nameW + Theme.D(4), ny, Theme.D(18), ns.Height);
nameZone = Rectangle.Union(new Rectangle(x, ny, nameW, ns.Height), penRect);
if (hl) Theme.Draw(g, Glyph.Edit, Theme.IconF(8.5f), penRect, Theme.Faint, Theme.Center);
Theme.Draw(g, detail, Theme.F(8.5f, false), new Rectangle(x, Theme.D(30), maxRight - x, Theme.D(18)), Theme.Faint, TextFormatFlags.EndEllipsis);
if (M.Active && !M.HdrSupported)
Theme.Draw(g, "—", Theme.F(9f, false), new Rectangle(Width - Theme.D(ColHdr), 0, TgHdr.Width, Height), Theme.Faint, Theme.Center);
}
}
/// Mini-carte de la disposition des ecrans.
class LayoutMap : Smooth
{
public class Item { public Monitor M; public int Number; public Rectangle R; }
List<Item> items = new List<Item>();
string sig = "";
public int Hover = -1;
public event EventHandler HoverChanged;
public event Action<int> ItemDoubleClicked;
readonly List<KeyValuePair<int, RectangleF>> drawn = new List<KeyValuePair<int, RectangleF>>();
public LayoutMap() { Height = Theme.D(112); }
public void SetItems(List<Item> list)
{
var sb = new System.Text.StringBuilder();
foreach (var it in list) sb.Append(it.Number).Append(it.R).Append(it.M.Active).Append(it.M.HdrOn).Append('|');
items = list;
if (sb.ToString() != sig) { sig = sb.ToString(); Invalidate(); }
}
protected override void OnPaint(PaintEventArgs e)
{
var g = e.Graphics; Theme.HQ(g); g.Clear(ParentBg);
Theme.Fill(g, new RectangleF(0, 0, Width, Height), Theme.D(8), Theme.Card);
drawn.Clear();
if (items.Count == 0) return;
var bb = items[0].R;
foreach (var it in items) bb = Rectangle.Union(bb, it.R);
float pad = Theme.D(14);
float sc = Math.Min((Width - 2 * pad) / bb.Width, (Height - 2 * pad) / bb.Height);
float ox = (Width - bb.Width * sc) / 2 - bb.X * sc, oy = (Height - bb.Height * sc) / 2 - bb.Y * sc;
float gap = Theme.D(2);
var nf = Theme.F(9.5f, true);
foreach (var it in items)
{
var rf = new RectangleF(ox + it.R.X * sc + gap, oy + it.R.Y * sc + gap, it.R.Width * sc - 2 * gap, it.R.Height * sc - 2 * gap);
drawn.Add(new KeyValuePair<int, RectangleF>(it.Number, rf));
bool hv = it.Number == Hover;
float rad = Theme.D(4);
if (it.M.Active) Theme.Fill(g, rf, rad, hv ? Theme.Faint : Theme.Border);
else Theme.Stroke(g, rf, rad, hv ? Theme.Dim : Theme.Faint, 1f, true);
if (hv) Theme.Stroke(g, rf, rad, Theme.Accent, Theme.D(1.5f), false);
Theme.Draw(g, it.Number.ToString(), nf, Rectangle.Round(rf), it.M.Active ? Theme.Text : Theme.Faint, Theme.Center);
if (it.M.Active && it.M.HdrOn)
using (var b = new SolidBrush(Theme.Accent)) g.FillEllipse(b, rf.Right - Theme.D(10), rf.Y + Theme.D(5), Theme.D(5), Theme.D(5));
}
}
int HitTest(Point pt)
{
for (int i = drawn.Count - 1; i >= 0; i--) if (drawn[i].Value.Contains(pt)) return drawn[i].Key;
return -1;
}
public void SetHover(int n) { if (Hover != n) { Hover = n; Invalidate(); } }
protected override void OnMouseMove(MouseEventArgs e)
{
base.OnMouseMove(e);
int h = HitTest(e.Location);
Cursor = h >= 0 ? Cursors.Hand : Cursors.Default;
if (h != Hover) { Hover = h; Invalidate(); if (HoverChanged != null) HoverChanged(this, EventArgs.Empty); }
}
protected override void OnMouseLeave(EventArgs e)
{
base.OnMouseLeave(e);
if (Hover != -1) { Hover = -1; Invalidate(); if (HoverChanged != null) HoverChanged(this, EventArgs.Empty); }
}
protected override void OnMouseDoubleClick(MouseEventArgs e)
{
base.OnMouseDoubleClick(e);
int h = HitTest(e.Location);
if (h >= 0 && ItemDoubleClicked != null) ItemDoubleClicked(h);
}
}
// ------------------------------------------------------------------ Menus sombres
class DarkColors : ProfessionalColorTable
{
public override Color ToolStripDropDownBackground { get { return Theme.Card; } }
public override Color ImageMarginGradientBegin { get { return Theme.Card; } }
public override Color ImageMarginGradientMiddle { get { return Theme.Card; } }
public override Color ImageMarginGradientEnd { get { return Theme.Card; } }
public override Color MenuBorder { get { return Theme.Border; } }
public override Color MenuItemBorder { get { return Theme.CardHover; } }
public override Color MenuItemSelected { get { return Theme.CardHover; } }
public override Color MenuItemSelectedGradientBegin { get { return Theme.CardHover; } }
public override Color MenuItemSelectedGradientEnd { get { return Theme.CardHover; } }
public override Color MenuItemPressedGradientBegin { get { return Theme.CardHover; } }
public override Color MenuItemPressedGradientEnd { get { return Theme.CardHover; } }
public override Color SeparatorDark { get { return Theme.Border; } }
public override Color SeparatorLight { get { return Theme.Card; } }
public override Color CheckBackground { get { return Theme.Card; } }
public override Color CheckSelectedBackground { get { return Theme.CardHover; } }
public override Color CheckPressedBackground { get { return Theme.CardHover; } }
public override Color ButtonSelectedBorder { get { return Theme.CardHover; } }
}
class DarkRenderer : ToolStripProfessionalRenderer
{
public static readonly DarkRenderer Instance = new DarkRenderer();
DarkRenderer() : base(new DarkColors()) { RoundedEdges = false; }
protected override void OnRenderItemText(ToolStripItemTextRenderEventArgs e)
{
e.TextColor = (e.Item.Tag as string) == "header" ? Theme.Faint : (e.Item.Enabled ? (e.Item.ForeColor == Theme.Danger ? Theme.Danger : Theme.Text) : Theme.Faint);
base.OnRenderItemText(e);
}
protected override void OnRenderArrow(ToolStripArrowRenderEventArgs e) { e.ArrowColor = Theme.Dim; base.OnRenderArrow(e); }
protected override void OnRenderItemCheck(ToolStripItemImageRenderEventArgs e)
{
var r = e.ImageRectangle; r.Inflate(Theme.D(3), Theme.D(3));
Theme.Draw(e.Graphics, Glyph.Check, Theme.IconF(8.5f), r, Theme.Accent, Theme.Center);
}
protected override void OnRenderSeparator(ToolStripSeparatorRenderEventArgs e)
{
int y = e.Item.Height / 2;
using (var pen = new Pen(Theme.Border)) e.Graphics.DrawLine(pen, Theme.D(8), y, e.Item.Width - Theme.D(8), y);
}
}
static class Menus
{
public static ContextMenuStrip Create()
{
var m = new ContextMenuStrip { Renderer = DarkRenderer.Instance, Font = Theme.F(9.5f, false), ShowImageMargin = true, ShowCheckMargin = false };
m.ImageScalingSize = new Size(Theme.D(16), Theme.D(16));
return m;
}
public static ToolStripMenuItem Item(string text, EventHandler click)
{
var i = new ToolStripMenuItem(text) { Padding = new Padding(0, Theme.D(2), 0, Theme.D(2)) };
if (click != null) i.Click += click;
return i;
}
public static ToolStripMenuItem Header(string text)
{
return new ToolStripMenuItem(text.ToUpperInvariant()) { Enabled = false, Tag = "header", Font = Theme.F(7.5f, true) };
}
public static ToolStripMenuItem Sub(string text)
{
var i = Item(text, null);
i.DropDown.Renderer = DarkRenderer.Instance; i.DropDown.Font = Theme.F(9.5f, false);
return i;
}
/// Vide un menu en liberant ses elements.
public static void Clear(ToolStrip m)
{
var old = new List<ToolStripItem>();
foreach (ToolStripItem i in m.Items) old.Add(i);
m.Items.Clear();
foreach (var i in old) i.Dispose();
}
}
// ------------------------------------------------------------------ Dialogues
class DarkForm : Form
{
public DarkForm()
{
BackColor = Theme.Bg; ForeColor = Theme.Text; Font = Theme.F(9.5f, false);
FormBorderStyle = FormBorderStyle.FixedDialog; MaximizeBox = false; MinimizeBox = false; ShowInTaskbar = false;
StartPosition = FormStartPosition.CenterParent; KeyPreview = true; AutoScaleMode = AutoScaleMode.None;
Icon = LogoArt.AppIcon(Theme.D(16));
}
protected override void OnHandleCreated(EventArgs e) { base.OnHandleCreated(e); Win.Style(Handle, Theme.Bg); }
protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); if (e.KeyCode == Keys.Escape) { DialogResult = DialogResult.Cancel; Close(); } }
}
static class Dialogs
{
public static string Prompt(IWin32Window owner, string title, string text, string def)
{
using (var f = new DarkForm { Text = title, ClientSize = new Size(Theme.D(400), Theme.D(150)) })
{
if (owner == null) { f.StartPosition = FormStartPosition.CenterScreen; f.TopMost = true; f.ShowInTaskbar = true; }
var l = new Label { Text = text, Location = new Point(Theme.D(20), Theme.D(18)), AutoSize = true, ForeColor = Theme.Dim };
var t = new TextBox { Text = def ?? "", Location = new Point(Theme.D(20), Theme.D(46)), Width = Theme.D(360), BackColor = Theme.Card, ForeColor = Theme.Text, BorderStyle = BorderStyle.FixedSingle, Font = Theme.F(10.5f, false) };
var ok = new Pill("Enregistrer") { Primary = true };
var cancel = new Pill("Annuler");
ok.Location = new Point(f.ClientSize.Width - Theme.D(20) - ok.Width, Theme.D(100));
cancel.Location = new Point(ok.Left - Theme.D(8) - cancel.Width, Theme.D(100));
ok.Click += (s, e) => { f.DialogResult = DialogResult.OK; f.Close(); };
cancel.Click += (s, e) => { f.DialogResult = DialogResult.Cancel; f.Close(); };
t.KeyDown += (s, e) => { if (e.KeyCode == Keys.Enter) { e.SuppressKeyPress = true; f.DialogResult = DialogResult.OK; f.Close(); } };
f.Controls.AddRange(new Control[] { l, t, ok, cancel });
f.Shown += (s, e) => { t.Focus(); t.SelectAll(); };
return f.ShowDialog(owner) == DialogResult.OK ? t.Text.Trim() : null;
}
}
public static void About(IWin32Window owner)
{
using (var f = new DarkForm { Text = "À propos", ClientSize = new Size(Theme.D(380), Theme.D(250)) })
{
f.Paint += (s, e) =>
{
var g = e.Graphics; Theme.HQ(g);
int ls = Theme.D(64), w = f.ClientSize.Width;
LogoArt.Draw(g, new RectangleF((w - ls) / 2f, Theme.D(22), ls, ls));
Theme.Draw(g, Brand.Name, Theme.F(13f, true), new Rectangle(0, Theme.D(98), w, Theme.D(28)), Theme.Text, TextFormatFlags.HorizontalCenter);
Theme.Draw(g, "Version " + Brand.Version + " · " + Brand.By, Theme.F(9f, false), new Rectangle(0, Theme.D(128), w, Theme.D(20)), Theme.Dim, TextFormatFlags.HorizontalCenter);
Theme.Draw(g, "Écrans et HDR en un clic · Windows 10 / 11", Theme.F(9f, false), new Rectangle(0, Theme.D(150), w, Theme.D(20)), Theme.Faint, TextFormatFlags.HorizontalCenter);
};
var ok = new Pill("OK") { Primary = true };
ok.Location = new Point((f.ClientSize.Width - ok.Width) / 2, Theme.D(196));
ok.Click += (s, e) => f.Close();
f.Controls.Add(ok);
f.ShowDialog(owner);
}
}
}
/// Grand numero affiche au centre d'un ecran ("Identifier").
class IdentifyForm : Form
{
readonly int number; readonly string name;
readonly Timer timer = new Timer { Interval = 2500 };
public IdentifyForm(Rectangle screen, int number, string name)
{
this.number = number; this.name = name;
FormBorderStyle = FormBorderStyle.None; ShowInTaskbar = false; TopMost = true; StartPosition = FormStartPosition.Manual;
BackColor = Theme.Bg; AutoScaleMode = AutoScaleMode.None; DoubleBuffered = true;
var sz = new Size(Theme.D(240), Theme.D(180));
Bounds = new Rectangle(screen.X + (screen.Width - sz.Width) / 2, screen.Y + (screen.Height - sz.Height) / 2, sz.Width, sz.Height);
timer.Tick += (s, e) => Close(); timer.Start();
Click += (s, e) => Close();
}
protected override bool ShowWithoutActivation { get { return true; } }
protected override void OnHandleCreated(EventArgs e) { base.OnHandleCreated(e); Win.Style(Handle, Theme.Bg); }
protected override void OnFormClosed(FormClosedEventArgs e) { timer.Dispose(); base.OnFormClosed(e); }
protected override void OnPaint(PaintEventArgs e)
{
var g = e.Graphics;
using (var pen = new Pen(Theme.Accent, Theme.D(2))) g.DrawRectangle(pen, Theme.D(1), Theme.D(1), Width - Theme.D(2) - 1, Height - Theme.D(2) - 1);
Theme.Draw(g, number.ToString(), Theme.F(60f, true), new Rectangle(0, Theme.D(10), Width, Theme.D(120)), Theme.Text, Theme.Center);
Theme.Draw(g, name, Theme.F(10.5f, false), new Rectangle(Theme.D(10), Theme.D(132), Width - Theme.D(20), Theme.D(30)), Theme.Dim, Theme.Center | TextFormatFlags.EndEllipsis);
}
}
}