Repository navigation
Expand file tree
/
Copy pathProgram.cs
More file actions
866 lines (765 loc) · 37.5 KB
/
Copy pathProgram.cs
File metadata and controls
866 lines (765 loc) · 37.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
using System;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Text;
using System.IO;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace ShutdownTimer
{
internal static class Program
{
[STAThread]
private static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MainForm());
}
}
/// <summary>Farben des dunklen Designs.</summary>
internal static class Theme
{
public static readonly Color Background = Color.FromArgb(32, 32, 32);
public static readonly Color Surface = Color.FromArgb(45, 45, 45);
public static readonly Color SurfaceHover = Color.FromArgb(58, 58, 58);
public static readonly Color SurfacePressed = Color.FromArgb(38, 38, 38);
public static readonly Color Border = Color.FromArgb(70, 70, 70);
public static readonly Color BorderFocus = Color.FromArgb(140, 140, 140);
public static readonly Color Text = Color.FromArgb(240, 240, 240);
public static readonly Color TextDim = Color.FromArgb(120, 120, 120);
public static readonly Color Accent = Color.FromArgb(196, 43, 28);
public static readonly Color AccentHover = Color.FromArgb(216, 59, 43);
public static readonly Color AccentPressed = Color.FromArgb(165, 35, 20);
/// <summary>Zentrierter Text mit Graustufen-Glättung (keine ClearType-Farbsäume auf farbigen Flächen).</summary>
public static void DrawCentered(Graphics g, string text, Font font, RectangleF r, Color color)
{
var old = g.TextRenderingHint;
g.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;
using (var sf = new StringFormat(StringFormat.GenericTypographic))
using (var b = new SolidBrush(color))
{
sf.Alignment = StringAlignment.Center;
sf.LineAlignment = StringAlignment.Center;
sf.FormatFlags |= StringFormatFlags.NoWrap;
g.DrawString(text, font, b, r, sf);
}
g.TextRenderingHint = old;
}
}
/// <summary>Flacher, selbst gezeichneter Button mit abgerundeten Ecken.</summary>
internal sealed class DarkButton : Button
{
private bool hover, pressed;
private bool primary;
public bool Primary { get => primary; set { primary = value; Invalidate(); } }
/// <summary>Zeichnet statt Text ein kleines Uhr-Symbol.</summary>
public bool ClockIcon { get; set; }
public DarkButton()
{
SetStyle(ControlStyles.UserPaint | ControlStyles.AllPaintingInWmPaint |
ControlStyles.OptimizedDoubleBuffer | ControlStyles.ResizeRedraw, true);
FlatStyle = FlatStyle.Flat;
ForeColor = Theme.Text;
BackColor = Theme.Background;
Cursor = Cursors.Hand;
AccessibleRole = AccessibleRole.PushButton;
}
protected override void OnMouseEnter(EventArgs e) { hover = true; Invalidate(); base.OnMouseEnter(e); }
protected override void OnMouseLeave(EventArgs e) { hover = false; pressed = false; Invalidate(); base.OnMouseLeave(e); }
protected override void OnMouseDown(MouseEventArgs e) { if (e.Button == MouseButtons.Left) { pressed = true; Invalidate(); } base.OnMouseDown(e); }
protected override void OnMouseUp(MouseEventArgs e) { pressed = false; Invalidate(); base.OnMouseUp(e); }
protected override void OnEnabledChanged(EventArgs e) { hover = pressed = false; Invalidate(); base.OnEnabledChanged(e); }
protected override void OnPaint(PaintEventArgs e)
{
var g = e.Graphics;
g.Clear(Parent?.BackColor ?? Theme.Background);
g.SmoothingMode = SmoothingMode.AntiAlias;
Color fill, border;
if (!Enabled) { fill = Theme.Background; border = Theme.Border; }
else if (Primary)
{
fill = pressed ? Theme.AccentPressed : hover ? Theme.AccentHover : Theme.Accent;
border = Focused ? Theme.Text : fill;
}
else
{
fill = pressed ? Theme.SurfacePressed : hover ? Theme.SurfaceHover : Theme.Surface;
border = Focused ? Theme.BorderFocus : Theme.Border;
}
var rect = new RectangleF(0.5f, 0.5f, Width - 1.5f, Height - 1.5f);
float radius = 5f * DeviceDpi / 96f;
using (var path = RoundedRect(rect, radius))
using (var brush = new SolidBrush(fill))
using (var pen = new Pen(border))
{
g.FillPath(brush, path);
g.DrawPath(pen, path);
}
Color fore = Enabled ? Theme.Text : Theme.TextDim;
if (ClockIcon)
{
float s = DeviceDpi / 96f;
float r = Math.Min(Width, Height) * 0.28f;
var c = new PointF(Width / 2f, Height / 2f);
using (var pen = new Pen(fore, 1.6f * s) { StartCap = LineCap.Round, EndCap = LineCap.Round })
{
g.DrawEllipse(pen, c.X - r, c.Y - r, 2 * r, 2 * r);
g.DrawLine(pen, c, new PointF(c.X, c.Y - r * 0.62f));
g.DrawLine(pen, c, new PointF(c.X + r * 0.48f, c.Y));
}
}
else
{
Theme.DrawCentered(g, Text, Font, ClientRectangle, fore);
}
}
private static GraphicsPath RoundedRect(RectangleF r, float radius)
{
float d = radius * 2;
var p = new GraphicsPath();
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;
}
}
/// <summary>Selbst gezeichneter Auswahlpunkt (Radio-Button) im dunklen Design.</summary>
internal sealed class DarkRadio : RadioButton
{
private bool hover;
public DarkRadio()
{
SetStyle(ControlStyles.UserPaint | ControlStyles.AllPaintingInWmPaint |
ControlStyles.OptimizedDoubleBuffer | ControlStyles.ResizeRedraw, true);
ForeColor = Theme.Text;
Cursor = Cursors.Hand;
AccessibleRole = AccessibleRole.RadioButton;
}
private float Scale1 => DeviceDpi / 96f;
private float Dot => 16 * Scale1;
public override Size GetPreferredSize(Size proposedSize)
{
Size t = TextRenderer.MeasureText(Text, Font);
return new Size((int)(Dot + 8 * Scale1) + t.Width, Math.Max(t.Height, (int)Dot) + (int)(4 * Scale1));
}
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 OnCheckedChanged(EventArgs e) { Invalidate(); base.OnCheckedChanged(e); }
protected override void OnPaint(PaintEventArgs e)
{
var g = e.Graphics;
g.Clear(Parent?.BackColor ?? Theme.Background);
g.SmoothingMode = SmoothingMode.AntiAlias;
float d = Dot, y = (Height - d) / 2f, x = 1.5f * Scale1;
Color ring = !Enabled ? Theme.Border : Checked ? Theme.Accent : hover ? Theme.Text : Color.FromArgb(150, 150, 150);
using (var pen = new Pen(ring, 1.6f * Scale1))
g.DrawEllipse(pen, x, y, d, d);
if (Checked)
{
float inset = d * 0.27f;
using (var b = new SolidBrush(Enabled ? Theme.Accent : Theme.Border))
g.FillEllipse(b, x + inset, y + inset, d - 2 * inset, d - 2 * inset);
}
var textRect = new Rectangle((int)(x + d + 6 * Scale1), 0, Width, Height);
TextRenderer.DrawText(g, Text, Font, textRect, Enabled ? Theme.Text : Theme.TextDim, Parent?.BackColor ?? Theme.Background,
TextFormatFlags.Left | TextFormatFlags.VerticalCenter | TextFormatFlags.SingleLine);
if (Focused && ShowFocusCues)
ControlPaint.DrawFocusRectangle(g, new Rectangle(textRect.X - 2, 1, Width - textRect.X + 1, Height - 2), Theme.Text, Parent?.BackColor ?? Theme.Background);
}
}
/// <summary>Zahlenfeld im dunklen Design (Pfeiltasten werden übermalt), optional mit führender Null.</summary>
internal sealed class DarkNumeric : NumericUpDown
{
private int hoverPart = -1; // 0 = oben, 1 = unten
private bool pressed;
public bool PadZero { get; set; }
public DarkNumeric()
{
BorderStyle = BorderStyle.None;
BackColor = Theme.Surface;
ForeColor = Theme.Text;
TextAlign = HorizontalAlignment.Center;
Control buttons = Controls[0]; // interne UpDownButtons
buttons.Paint += PaintButtons;
buttons.MouseMove += (s, e) => { int part = e.Y < buttons.Height / 2 ? 0 : 1; if (part != hoverPart) { hoverPart = part; buttons.Invalidate(); } };
buttons.MouseLeave += (s, e) => { hoverPart = -1; pressed = false; buttons.Invalidate(); };
buttons.MouseDown += (s, e) => { pressed = true; buttons.Invalidate(); };
buttons.MouseUp += (s, e) => { pressed = false; buttons.Invalidate(); };
}
protected override void UpdateEditText()
{
if (PadZero) Text = ((int)Value).ToString("00");
else base.UpdateEditText();
}
private void PaintButtons(object sender, PaintEventArgs e)
{
var c = (Control)sender;
var g = e.Graphics;
g.SmoothingMode = SmoothingMode.AntiAlias;
g.Clear(Theme.Surface);
int half = c.Height / 2;
var top = new Rectangle(0, 0, c.Width, half);
var bottom = new Rectangle(0, half, c.Width, c.Height - half);
if (Enabled && hoverPart >= 0)
using (var b = new SolidBrush(pressed ? Theme.SurfacePressed : Theme.SurfaceHover))
g.FillRectangle(b, hoverPart == 0 ? top : bottom);
Color arrow = Enabled ? Theme.Text : Theme.TextDim;
DrawArrow(g, top, true, arrow);
DrawArrow(g, bottom, false, arrow);
}
private static void DrawArrow(Graphics g, Rectangle r, bool up, Color color)
{
float w = Math.Max(3f, r.Width * 0.22f), h = w * 0.6f;
float cx = r.X + r.Width / 2f, cy = r.Y + r.Height / 2f;
PointF[] pts = up
? new[] { new PointF(cx - w, cy + h / 2), new PointF(cx + w, cy + h / 2), new PointF(cx, cy - h / 2) }
: new[] { new PointF(cx - w, cy - h / 2), new PointF(cx + w, cy - h / 2), new PointF(cx, cy + h / 2) };
using (var b = new SolidBrush(color)) g.FillPolygon(b, pts);
}
}
/// <summary>
/// Aufklappbare Uhrzeitauswahl mit Ziffernblatt (24 h):
/// erst Stunde wählen (außen 1–12, innen 13–00), danach springt sie automatisch zu den Minuten.
/// </summary>
internal sealed class ClockPicker : Control
{
private static readonly Color Card = Color.FromArgb(40, 40, 40);
private static readonly Color Dial = Color.FromArgb(58, 58, 58);
private static readonly Color InnerText = Color.FromArgb(175, 175, 175);
private readonly Font numFont = new Font("Segoe UI", 11f);
private readonly Font innerFont = new Font("Segoe UI", 8.5f);
private readonly DarkButton btnOk = new DarkButton { Text = "Okay", Primary = true, Size = new Size(84, 32) };
private readonly DarkButton btnCancel = new DarkButton { Text = "Abbrechen", Size = new Size(96, 32) };
private int hour, minute;
private bool minuteMode, dragging;
public event EventHandler ValueChanged;
/// <summary>Wechsel zwischen Stunden- und Minutenansicht.</summary>
public event EventHandler ModeChanged;
/// <summary>true = Okay, false = Abbrechen</summary>
public event Action<bool> CloseRequested;
public ClockPicker()
{
SetStyle(ControlStyles.UserPaint | ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer |
ControlStyles.ResizeRedraw | ControlStyles.Selectable, true);
BackColor = Card;
ForeColor = Theme.Text;
Size = new Size(276, 326); // kompakt, damit es auch auf kleinen Bildschirmen (z. B. 1280x720) passt
btnOk.Font = btnCancel.Font = new Font("Segoe UI Semibold", 10f);
btnOk.Click += (s, e) => CloseRequested?.Invoke(true);
btnCancel.Click += (s, e) => CloseRequested?.Invoke(false);
Controls.Add(btnCancel);
Controls.Add(btnOk);
}
public int Hour => hour;
public int Minute => minute;
public void SetTime(int h, int m)
{
hour = ((h % 24) + 24) % 24;
minute = ((m % 60) + 60) % 60;
Invalidate();
}
public bool MinuteMode => minuteMode;
public void ShowHours() => SetMode(false);
public void ShowMinutes() => SetMode(true);
private void SetMode(bool minutes)
{
if (minuteMode == minutes) return;
minuteMode = minutes;
Invalidate();
ModeChanged?.Invoke(this, EventArgs.Empty);
}
// Alle Maße relativ zur Breite -> skaliert automatisch mit der DPI-Einstellung
private float S => Width / 276f;
private float DialR => 126 * S;
private float OuterR => 102 * S;
private float InnerR => 68 * S;
private float KnobR => 18 * S;
private PointF Center => new PointF(Width / 2f, 12 * S + DialR);
protected override void OnLayout(LayoutEventArgs e)
{
base.OnLayout(e);
int pad = (int)(12 * S);
// Abbrechen links, Okay rechts, direkt unter dem Ziffernblatt
btnCancel.Location = new Point(pad, Height - pad - btnCancel.Height);
btnOk.Location = new Point(Width - pad - btnOk.Width, btnCancel.Top);
}
protected override void OnPaint(PaintEventArgs e)
{
var g = e.Graphics;
g.Clear(Parent?.BackColor ?? Theme.Background);
g.SmoothingMode = SmoothingMode.AntiAlias;
// Karte
using (var path = Round(new RectangleF(0.5f, 0.5f, Width - 1.5f, Height - 1.5f), 8 * S))
using (var b = new SolidBrush(Card))
using (var p = new Pen(Theme.Border))
{
g.FillPath(b, path);
g.DrawPath(p, path);
}
// Ziffernblatt
PointF c = Center;
using (var b = new SolidBrush(Dial))
g.FillEllipse(b, c.X - DialR, c.Y - DialR, 2 * DialR, 2 * DialR);
float selAngle, selR;
if (minuteMode) { selAngle = minute * 6; selR = OuterR; }
else { selAngle = (hour % 12) * 30; selR = (hour == 0 || hour > 12) ? InnerR : OuterR; }
PointF knob = Polar(selAngle, selR);
using (var accent = new SolidBrush(Theme.Accent))
using (var hand = new Pen(Theme.Accent, 2 * S))
{
g.DrawLine(hand, c, knob);
g.FillEllipse(accent, c.X - 4 * S, c.Y - 4 * S, 8 * S, 8 * S);
g.FillEllipse(accent, knob.X - KnobR, knob.Y - KnobR, 2 * KnobR, 2 * KnobR);
}
for (int i = 0; i < 12; i++)
{
if (minuteMode)
{
DrawLabel(g, (i * 5).ToString("00"), numFont, Polar(i * 30, OuterR), Theme.Text, minute == i * 5);
}
else
{
int outerHour = i == 0 ? 12 : i, innerHour = i == 0 ? 0 : i + 12;
DrawLabel(g, outerHour.ToString(), numFont, Polar(i * 30, OuterR), Theme.Text, hour == outerHour);
DrawLabel(g, innerHour.ToString("00"), innerFont, Polar(i * 30, InnerR), InnerText, hour == innerHour);
}
}
// Minute zwischen den 5er-Schritten: kleiner Punkt im Knopf
if (minuteMode && minute % 5 != 0)
using (var w = new SolidBrush(Theme.Text))
g.FillEllipse(w, knob.X - 3 * S, knob.Y - 3 * S, 6 * S, 6 * S);
}
private void DrawLabel(Graphics g, string text, Font font, PointF p, Color color, bool selected)
{
var r = new RectangleF(p.X - 20 * S, p.Y - 12 * S, 40 * S, 24 * S);
Theme.DrawCentered(g, text, font, r, selected ? Theme.Text : color);
}
private PointF Polar(float degrees, float radius)
{
double rad = degrees * Math.PI / 180;
PointF c = Center;
return new PointF(c.X + radius * (float)Math.Sin(rad), c.Y - radius * (float)Math.Cos(rad));
}
private static GraphicsPath Round(RectangleF r, float radius)
{
float d = radius * 2;
var p = new GraphicsPath();
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;
}
protected override void OnMouseDown(MouseEventArgs e)
{
base.OnMouseDown(e);
Focus();
if (e.Button != MouseButtons.Left) return;
float dx = e.X - Center.X, dy = e.Y - Center.Y;
if (Math.Sqrt(dx * dx + dy * dy) <= DialR + 6 * S)
{
dragging = true;
Apply(e.Location);
}
}
protected override void OnMouseMove(MouseEventArgs e)
{
base.OnMouseMove(e);
if (dragging) Apply(e.Location);
float dx = e.X - Center.X, dy = e.Y - Center.Y;
bool overDial = Math.Sqrt(dx * dx + dy * dy) <= DialR + 6 * S;
Cursor = overDial ? Cursors.Hand : Cursors.Default;
}
protected override void OnMouseUp(MouseEventArgs e)
{
base.OnMouseUp(e);
if (!dragging) return;
dragging = false;
Apply(e.Location);
if (!minuteMode) SetMode(true); // wie beim Android-Wecker: weiter zu den Minuten
}
protected override void OnMouseWheel(MouseEventArgs e)
{
base.OnMouseWheel(e);
int step = e.Delta > 0 ? 1 : -1;
if (minuteMode) SetTime(hour, minute + step);
else SetTime(hour + step, minute);
ValueChanged?.Invoke(this, EventArgs.Empty);
}
private void Apply(Point p)
{
float dx = p.X - Center.X, dy = p.Y - Center.Y;
double angle = Math.Atan2(dx, -dy) * 180 / Math.PI;
if (angle < 0) angle += 360;
double dist = Math.Sqrt(dx * dx + dy * dy);
int h = hour, m = minute;
if (minuteMode)
{
m = (int)Math.Round(angle / 6) % 60;
}
else
{
int idx = (int)Math.Round(angle / 30) % 12;
bool inner = dist < (OuterR + InnerR) / 2;
h = inner ? (idx == 0 ? 0 : idx + 12) : (idx == 0 ? 12 : idx);
}
if (h != hour || m != minute)
{
SetTime(h, m);
ValueChanged?.Invoke(this, EventArgs.Empty);
}
}
}
internal sealed class MainForm : Form
{
// Windows-Fehlercodes von shutdown.exe
private const int ERROR_SHUTDOWN_IS_SCHEDULED = 1190;
private const int ERROR_NO_SHUTDOWN_IN_PROGRESS = 1116;
private const int MaxShutdownSeconds = 315360000; // Obergrenze von shutdown /t (10 Jahre)
private readonly DarkRadio rbDuration = new DarkRadio { Text = "Herunterfahren in:", AutoSize = true, Checked = true, Margin = new Padding(3, 7, 6, 3) };
private readonly DarkRadio rbTime = new DarkRadio { Text = "Herunterfahren um:", AutoSize = true, Margin = new Padding(3, 7, 6, 3) };
private readonly DarkNumeric nudHours = new DarkNumeric { Minimum = 0, Maximum = 99, Width = 56 };
private readonly DarkNumeric nudMinutes = new DarkNumeric { Minimum = 0, Maximum = 59, Value = 30, Width = 56 };
private readonly DarkNumeric nudAtHour = new DarkNumeric { Minimum = 0, Maximum = 23, Width = 56, PadZero = true };
private readonly DarkNumeric nudAtMinute = new DarkNumeric { Minimum = 0, Maximum = 59, Width = 56, PadZero = true };
private readonly DarkButton btnClock = new DarkButton
{
ClockIcon = true, Size = new Size(34, 30), Margin = new Padding(2, 4, 3, 3),
AccessibleName = "Uhrzeit auf dem Ziffernblatt wählen"
};
private readonly ToolTip toolTip = new ToolTip();
private bool syncingTime;
private readonly ClockPicker clockPicker = new ClockPicker { Visible = false, Anchor = AnchorStyles.None, Margin = new Padding(3, 6, 3, 4) };
private int backupHour, backupMinute;
private readonly DarkButton btnStart = new DarkButton { Text = "Start", Size = new Size(150, 44), Primary = true };
private readonly DarkButton btnCancel = new DarkButton { Text = "Abbrechen", Size = new Size(150, 44), Enabled = false };
private readonly Label lblStatus = new Label { AutoSize = true, Text = "Kein Timer aktiv.", Anchor = AnchorStyles.None, Margin = new Padding(3, 10, 3, 3) };
private readonly Timer uiTimer = new Timer { Interval = 500 };
private readonly FlowLayoutPanel rowPresets = Flow();
private DateTime? targetUtc;
private bool fallbackTriggered;
public MainForm()
{
SuspendLayout();
AutoScaleDimensions = new SizeF(96F, 96F);
AutoScaleMode = AutoScaleMode.Dpi;
Text = "Shutdown Timer";
Font = new Font("Segoe UI", 10f);
BackColor = Theme.Background;
ForeColor = Theme.Text;
FormBorderStyle = FormBorderStyle.FixedSingle;
MaximizeBox = false;
StartPosition = FormStartPosition.Manual; // Position wird in OnLoad gesetzt (oben mittig)
AutoSize = true;
AutoSizeMode = AutoSizeMode.GrowAndShrink;
Padding = new Padding(14);
try { Icon = Icon.ExtractAssociatedIcon(Application.ExecutablePath); } catch { /* egal */ }
DateTime inOneHour = DateTime.Now.AddHours(1);
SetTime(inOneHour.Hour, inOneHour.Minute);
toolTip.SetToolTip(btnClock, "Uhrzeit auf dem Ziffernblatt wählen");
var buttonFont = new Font("Segoe UI Semibold", 11f);
btnStart.Font = btnCancel.Font = buttonFont;
lblStatus.Font = new Font("Segoe UI Semibold", 10.5f);
var root = new TableLayoutPanel { AutoSize = true, ColumnCount = 1, Dock = DockStyle.Fill };
// Zeile 1: Dauer manuell
var rowDuration = Flow();
rowDuration.Controls.Add(rbDuration);
AddNumeric(rowDuration, nudHours);
rowDuration.Controls.Add(SmallLabel("Std."));
AddNumeric(rowDuration, nudMinutes);
rowDuration.Controls.Add(SmallLabel("Min."));
root.Controls.Add(rowDuration);
// Zeile 2: Schnellauswahl
rowPresets.Padding = new Padding(20, 4, 0, 8);
AddPreset("15 Min", 0, 15);
AddPreset("30 Min", 0, 30);
AddPreset("1 Std", 1, 0);
AddPreset("2 Std", 2, 0);
AddPreset("3 Std", 3, 0);
root.Controls.Add(rowPresets);
// Zeile 3: Uhrzeit
var rowTime = Flow();
rowTime.Controls.Add(rbTime);
AddNumeric(rowTime, nudAtHour);
rowTime.Controls.Add(new Label { Text = ":", AutoSize = true, Margin = new Padding(0, 7, 0, 0) });
AddNumeric(rowTime, nudAtMinute);
rowTime.Controls.Add(SmallLabel("Uhr"));
rowTime.Controls.Add(btnClock);
root.Controls.Add(rowTime);
// Aufklappbares Ziffernblatt (direkt unter der Uhrzeit-Zeile)
root.Controls.Add(clockPicker);
// Zeile 4: Start/Abbrechen zentriert
var rowButtons = Flow();
rowButtons.Anchor = AnchorStyles.None;
rowButtons.Padding = new Padding(0, 14, 0, 0);
btnStart.Margin = new Padding(6, 0, 6, 0);
btnCancel.Margin = new Padding(6, 0, 6, 0);
rowButtons.Controls.Add(btnStart);
rowButtons.Controls.Add(btnCancel);
root.Controls.Add(rowButtons);
// Zeile 5: Status
root.Controls.Add(lblStatus);
Controls.Add(root);
// Die beiden Optionen liegen in verschiedenen Containern -> gegenseitig ausschließen per Hand
rbDuration.CheckedChanged += (s, e) => { if (rbDuration.Checked) { rbTime.Checked = false; SetClockOpen(false); } };
// Klick in den Bereich "Herunterfahren in" klappt das Ziffernblatt automatisch zu (Uhrzeit bleibt erhalten)
nudHours.Enter += (s, e) => SetClockOpen(false);
nudMinutes.Enter += (s, e) => SetClockOpen(false);
rbTime.CheckedChanged += (s, e) => { if (rbTime.Checked) rbDuration.Checked = false; };
nudHours.ValueChanged += (s, e) => rbDuration.Checked = true;
nudMinutes.ValueChanged += (s, e) => rbDuration.Checked = true;
// Manuelle Eingabe und Ziffernblatt bleiben synchron
EventHandler fieldsChanged = (s, e) =>
{
if (syncingTime) return;
rbTime.Checked = true;
clockPicker.SetTime((int)nudAtHour.Value, (int)nudAtMinute.Value);
};
nudAtHour.ValueChanged += fieldsChanged;
nudAtMinute.ValueChanged += fieldsChanged;
clockPicker.ValueChanged += (s, e) => { rbTime.Checked = true; SetTime(clockPicker.Hour, clockPicker.Minute); };
btnClock.Click += (s, e) => SetClockOpen(!clockPicker.Visible);
// Klick ins Stunden-/Minutenfeld wechselt die Ansicht des Ziffernblatts
nudAtHour.Enter += (s, e) => clockPicker.ShowHours();
nudAtMinute.Enter += (s, e) => clockPicker.ShowMinutes();
clockPicker.ModeChanged += (s, e) => nudAtHour.Parent?.Invalidate();
clockPicker.CloseRequested += ok =>
{
if (!ok) SetTime(backupHour, backupMinute);
SetClockOpen(false);
};
btnStart.Click += (s, e) => StartTimer();
btnCancel.Click += (s, e) => CancelTimer(showErrors: true);
uiTimer.Tick += (s, e) => UpdateCountdown();
AcceptButton = btnStart;
ResumeLayout(true);
}
private static FlowLayoutPanel Flow() =>
new FlowLayoutPanel { AutoSize = true, WrapContents = false, Margin = new Padding(0) };
private static Label SmallLabel(string text) =>
new Label { Text = text, AutoSize = true, Margin = new Padding(2, 7, 10, 0) };
/// <summary>Fügt ein Zahlenfeld hinzu und zeichnet einen dunklen Rahmen darum.</summary>
private void AddNumeric(FlowLayoutPanel panel, DarkNumeric nud)
{
nud.Margin = new Padding(4, 7, 4, 4);
panel.Controls.Add(nud);
panel.Paint += (s, e) =>
{
var r = nud.Bounds;
r.Inflate(3, 3);
r.Width -= 1; r.Height -= 1;
Color border = IsClockTarget(nud) ? Theme.Accent : nud.ContainsFocus ? Theme.BorderFocus : Theme.Border;
using (var bg = new SolidBrush(Theme.Surface)) e.Graphics.FillRectangle(bg, r);
using (var pen = new Pen(border)) e.Graphics.DrawRectangle(pen, r);
};
nud.Enter += (s, e) => panel.Invalidate();
nud.Leave += (s, e) => panel.Invalidate();
}
private void AddPreset(string text, int hours, int minutes)
{
var b = new DarkButton { Text = text, Size = new Size(76, 36), Margin = new Padding(3, 3, 5, 3) };
b.Click += (s, e) =>
{
nudHours.Value = hours;
nudMinutes.Value = minutes;
rbDuration.Checked = true;
SetClockOpen(false);
};
rowPresets.Controls.Add(b);
}
// --- Fensterposition: oben mittig öffnen und immer vollständig auf dem Bildschirm halten ---
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
Rectangle wa = Screen.FromPoint(Cursor.Position).WorkingArea;
int margin = (int)(24 * DeviceDpi / 96f);
Location = new Point(wa.Left + (wa.Width - Width) / 2, wa.Top + Math.Min(margin, Math.Max(0, wa.Height - Height)));
}
protected override void OnSizeChanged(EventArgs e)
{
base.OnSizeChanged(e);
if (!IsHandleCreated || WindowState != FormWindowState.Normal) return;
Rectangle wa = Screen.FromControl(this).WorkingArea;
int top = Top, left = Left;
if (Bottom > wa.Bottom) top = Math.Max(wa.Top, wa.Bottom - Height); // nach oben schieben, wenn unten abgeschnitten
if (Right > wa.Right) left = Math.Max(wa.Left, wa.Right - Width);
if (top != Top || left != Left) Location = new Point(left, top);
}
private void SetClockOpen(bool open)
{
if (open && !clockPicker.Visible)
{
backupHour = clockPicker.Hour;
backupMinute = clockPicker.Minute;
clockPicker.ShowHours();
rbTime.Checked = true;
}
clockPicker.Visible = open;
btnClock.Primary = open; // Button rot hervorheben, solange das Ziffernblatt offen ist
nudAtHour.Parent?.Invalidate();
if (open) clockPicker.Focus();
}
/// <summary>Feld, das gerade auf dem Ziffernblatt eingestellt wird (roter Rahmen).</summary>
private bool IsClockTarget(DarkNumeric nud) =>
clockPicker.Visible &&
((nud == nudAtHour && !clockPicker.MinuteMode) || (nud == nudAtMinute && clockPicker.MinuteMode));
/// <summary>Setzt die Uhrzeit in Eingabefeldern und Ziffernblatt gleichzeitig.</summary>
private void SetTime(int hour, int minute)
{
syncingTime = true;
try
{
nudAtHour.Value = hour;
nudAtMinute.Value = minute;
clockPicker.SetTime(hour, minute);
}
finally { syncingTime = false; }
}
// --- Dunkle Titelleiste (Windows 10 20H1+ / Windows 11) ---
[DllImport("dwmapi.dll")]
private static extern int DwmSetWindowAttribute(IntPtr hwnd, int attr, ref int value, int size);
protected override void OnHandleCreated(EventArgs e)
{
base.OnHandleCreated(e);
int on = 1;
if (DwmSetWindowAttribute(Handle, 20, ref on, sizeof(int)) != 0) // DWMWA_USE_IMMERSIVE_DARK_MODE
DwmSetWindowAttribute(Handle, 19, ref on, sizeof(int)); // ältere Windows-10-Builds
}
private TimeSpan GetRequestedDelay()
{
if (rbDuration.Checked)
return new TimeSpan((int)nudHours.Value, (int)nudMinutes.Value, 0);
DateTime now = DateTime.Now;
DateTime target = now.Date.Add(new TimeSpan((int)nudAtHour.Value, (int)nudAtMinute.Value, 0));
if (target <= now) target = target.AddDays(1); // Uhrzeit schon vorbei -> morgen
return target - now;
}
private void StartTimer()
{
if (clockPicker.Visible) SetClockOpen(false); // gewählte Uhrzeit übernehmen
TimeSpan delay = GetRequestedDelay();
int seconds = (int)Math.Ceiling(delay.TotalSeconds);
if (seconds < 1)
{
MessageBox.Show(this, "Bitte eine Zeit größer als 0 wählen.", Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
if (seconds > MaxShutdownSeconds) seconds = MaxShutdownSeconds;
// Windows selbst plant den Shutdown -> läuft auch weiter, wenn dieses Programm beendet wird oder abstürzt.
// /f erzwingt das Schließen von Programmen, damit nichts den Shutdown blockiert.
int code = RunShutdown($"/s /f /t {seconds} /c \"Geplanter Shutdown durch Shutdown Timer\"");
if (code == ERROR_SHUTDOWN_IS_SCHEDULED)
{
var answer = MessageBox.Show(this,
"Es ist bereits ein Herunterfahren geplant (evtl. von einem anderen Programm).\n\nDiesen ersetzen?",
Text, MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (answer != DialogResult.Yes) return;
RunShutdown("/a");
code = RunShutdown($"/s /f /t {seconds} /c \"Geplanter Shutdown durch Shutdown Timer\"");
}
if (code != 0)
{
MessageBox.Show(this, $"Shutdown konnte nicht geplant werden (Fehlercode {code}).",
Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
targetUtc = DateTime.UtcNow.AddSeconds(seconds);
fallbackTriggered = false;
KeepAwake(true); // verhindert Standby, damit der Countdown nicht "einfriert"
SetRunningUi(true);
UpdateCountdown();
uiTimer.Start();
}
private void CancelTimer(bool showErrors)
{
int code = RunShutdown("/a");
uiTimer.Stop();
targetUtc = null;
KeepAwake(false);
SetRunningUi(false);
lblStatus.Text = "Timer abgebrochen.";
if (showErrors && code != 0 && code != ERROR_NO_SHUTDOWN_IN_PROGRESS)
MessageBox.Show(this, $"Abbrechen fehlgeschlagen (Fehlercode {code}).", Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
private void UpdateCountdown()
{
if (targetUtc == null) return;
TimeSpan left = targetUtc.Value - DateTime.UtcNow;
if (left <= TimeSpan.Zero)
{
lblStatus.Text = "Fahre herunter ...";
// Sicherheitsnetz: falls der Windows-Timer nicht gegriffen hat, sofort herunterfahren.
if (!fallbackTriggered && left < TimeSpan.FromSeconds(-5))
{
fallbackTriggered = true;
RunShutdown("/s /f /t 0");
}
return;
}
DateTime localTarget = targetUtc.Value.ToLocalTime();
string when = localTarget.Date == DateTime.Today
? localTarget.ToString("HH:mm:ss")
: localTarget.ToString("ddd dd.MM. HH:mm:ss");
lblStatus.Text = $"Herunterfahren in {(int)left.TotalHours:00}:{left.Minutes:00}:{left.Seconds:00} (um {when})";
}
private void SetRunningUi(bool running)
{
btnStart.Enabled = !running;
btnCancel.Enabled = running;
rbDuration.Enabled = rbTime.Enabled = !running;
nudHours.Enabled = nudMinutes.Enabled = nudAtHour.Enabled = nudAtMinute.Enabled = btnClock.Enabled = !running;
rowPresets.Enabled = !running;
AcceptButton = running ? null : btnStart;
if (running) btnCancel.Focus();
}
protected override void OnFormClosing(FormClosingEventArgs e)
{
if (targetUtc != null && e.CloseReason == CloseReason.UserClosing)
{
var answer = MessageBox.Show(this,
"Der Timer läuft noch.\n\n" +
"Ja = Timer abbrechen und beenden\n" +
"Nein = Beenden, Herunterfahren bleibt geplant\n" +
"Abbrechen = Programm offen lassen",
Text, MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
if (answer == DialogResult.Cancel) { e.Cancel = true; return; }
if (answer == DialogResult.Yes) CancelTimer(showErrors: false);
}
KeepAwake(false);
base.OnFormClosing(e);
}
private static int RunShutdown(string args)
{
try
{
var psi = new ProcessStartInfo(Path.Combine(Environment.SystemDirectory, "shutdown.exe"), args)
{
UseShellExecute = false,
CreateNoWindow = true,
WindowStyle = ProcessWindowStyle.Hidden
};
using (var p = Process.Start(psi))
{
p.WaitForExit(15000);
return p.HasExited ? p.ExitCode : -1;
}
}
catch (Exception)
{
return -1;
}
}
// --- Standby verhindern, solange der Timer läuft ---
[DllImport("kernel32.dll")]
private static extern uint SetThreadExecutionState(uint esFlags);
private const uint ES_CONTINUOUS = 0x80000000;
private const uint ES_SYSTEM_REQUIRED = 0x00000001;
private static void KeepAwake(bool on) =>
SetThreadExecutionState(on ? ES_CONTINUOUS | ES_SYSTEM_REQUIRED : ES_CONTINUOUS);
}
}