Repository navigation
Expand file tree
/
Copy pathProgram.cs
More file actions
610 lines (504 loc) · 23.6 KB
/
Copy pathProgram.cs
File metadata and controls
610 lines (504 loc) · 23.6 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
// Pulsebar — shows live "CPU xx%" / "RAM xx%" on the Windows 11 taskbar, just left of the
// system tray / clock, in a small transparent overlay window (two stacked lines, like the clock).
// .NET 10 WinForms, no NuGet packages, no third-party code, no Explorer injection or hooks.
using System.Diagnostics;
using System.Drawing.Imaging;
using System.Drawing.Text;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Text;
using Microsoft.Win32;
namespace Pulsebar;
internal static class Program
{
[STAThread]
private static void Main()
{
// Single instance: if another copy owns the mutex, exit silently.
using var mutex = new Mutex(initiallyOwned: true, @"Local\P4.Pulsebar", out bool createdNew);
if (!createdNew) return;
ApplicationConfiguration.Initialize();
// No MainForm: the context owns the overlay and decides when the loop ends (Exit menu item).
// Disposal happens after Application.Run returns, never while a menu handler is running.
using (var context = new MonitorContext())
Application.Run(context);
mutex.ReleaseMutex();
}
}
/// <summary>Owns the taskbar overlay, the refresh timer, the context menu and the tooltip.</summary>
internal sealed class MonitorContext : ApplicationContext
{
private const string RunKeyPath = @"Software\Microsoft\Windows\CurrentVersion\Run";
private const string ThemeKeyPath = @"Software\Microsoft\Windows\CurrentVersion\Themes\Personalize";
private const string AppName = "Pulsebar";
// Tiny bilingual string table: T("English", "Español").
private static readonly bool IsSpanish = CultureInfo.CurrentUICulture.TwoLetterISOLanguageName == "es";
private static string T(string en, string es) => IsSpanish ? es : en;
private readonly OverlayForm _overlay = new();
private readonly ContextMenuStrip _menu = new();
private readonly ToolStripMenuItem _startupItem;
private readonly ToolTip _toolTip = new() { ShowAlways = true, InitialDelay = 400, ReshowDelay = 200 };
private readonly System.Windows.Forms.Timer _timer = new() { Interval = 1000 };
private long _prevIdle, _prevKernel, _prevUser; // last GetSystemTimes sample
private volatile bool _themeDirty = true; // set by UserPreferenceChanged (any thread)
private Color _textColor = Color.White;
private string _lastTip = string.Empty;
private bool _stopping, _disposed;
public MonitorContext()
{
// Context menu (default system rendering, no dark mode).
_startupItem = new ToolStripMenuItem(T("Start with Windows", "Iniciar con Windows"));
_startupItem.Checked = IsStartupEnabled();
_startupItem.Click += (_, _) => ToggleStartup();
_menu.Items.Add(_startupItem);
_menu.Items.Add(T("Task Manager", "Administrador de tareas"), null, (_, _) => OpenTaskManager());
_menu.Items.Add(new ToolStripSeparator());
_menu.Items.Add(T("Exit", "Salir"), null, (_, _) => ExitThread());
_overlay.MouseUp += (_, e) => { if (e.Button == MouseButtons.Right) ShowMenu(); };
_overlay.MouseDoubleClick += (_, e) => { if (e.Button == MouseButtons.Left) OpenTaskManager(); };
SystemEvents.UserPreferenceChanged += OnUserPreferenceChanged;
// Prime the CPU baseline and draw once, then refresh every second.
SampleCpu();
UpdateDisplay(cpuPercent: 0);
_timer.Tick += (_, _) => UpdateDisplay(SampleCpu());
_timer.Start();
}
// ---------------------------------------------------------------- metrics
/// <summary>Returns CPU usage % since the previous call (kernel time includes idle).</summary>
private double SampleCpu()
{
if (!Native.GetSystemTimes(out var idleFt, out var kernelFt, out var userFt)) return 0;
long idle = idleFt.ToLong(), kernel = kernelFt.ToLong(), user = userFt.ToLong();
long idleDelta = idle - _prevIdle;
long totalDelta = (kernel - _prevKernel) + (user - _prevUser);
(_prevIdle, _prevKernel, _prevUser) = (idle, kernel, user);
if (totalDelta <= 0) return 0;
return Math.Clamp((1.0 - (double)idleDelta / totalDelta) * 100.0, 0, 100);
}
private static (uint load, double usedGb, double totalGb) SampleRam()
{
var ms = new Native.MEMORYSTATUSEX { dwLength = (uint)Marshal.SizeOf<Native.MEMORYSTATUSEX>() };
if (!Native.GlobalMemoryStatusEx(ref ms)) return (0, 0, 0);
const double Gb = 1024d * 1024d * 1024d;
return (ms.dwMemoryLoad, (ms.ullTotalPhys - ms.ullAvailPhys) / Gb, ms.ullTotalPhys / Gb);
}
// ---------------------------------------------------------------- display
private void UpdateDisplay(double cpuPercent)
{
if (_stopping || _overlay.IsDisposed) return;
if (_themeDirty)
{
_themeDirty = false;
_textColor = IsLightTaskbar() ? Color.FromArgb(0x1A, 0x1A, 0x1A) : Color.White;
}
var (ramLoad, usedGb, totalGb) = SampleRam();
int cpu = Math.Clamp((int)Math.Round(cpuPercent), 0, 100);
int ram = (int)Math.Min(ramLoad, 100u);
// While the menu is open, don't re-raise the overlay over it.
_overlay.UpdateDisplay(cpu, ram, _textColor, menuOpen: _menu.Visible);
string tip = $"CPU {cpu}%\nRAM {ram}% · {usedGb:N1} / {totalGb:N1} GB";
if (tip != _lastTip)
{
_lastTip = tip;
_toolTip.SetToolTip(_overlay, tip);
}
}
private static bool IsLightTaskbar()
{
using var key = Registry.CurrentUser.OpenSubKey(ThemeKeyPath);
return key?.GetValue("SystemUsesLightTheme") is int v && v == 1;
}
// May be raised on a SystemEvents thread: only flag it; the UI timer re-reads the theme.
private void OnUserPreferenceChanged(object? sender, UserPreferenceChangedEventArgs e) => _themeDirty = true;
// ---------------------------------------------------------------- menu actions
private void ShowMenu()
{
if (_stopping || _overlay.IsDisposed) return;
// Like NotifyIcon does: make our app foreground so the menu closes when the user clicks elsewhere.
// (WS_EX_NOACTIVATE blocks click-activation, not an explicit SetForegroundWindow.)
Native.SetForegroundWindow(_overlay.Handle);
_menu.Show(Cursor.Position, ToolStripDropDownDirection.AboveLeft);
}
private static bool IsStartupEnabled()
{
using var key = Registry.CurrentUser.OpenSubKey(RunKeyPath);
return key?.GetValue(AppName) is string;
}
private void ToggleStartup()
{
try
{
using var key = Registry.CurrentUser.CreateSubKey(RunKeyPath, writable: true);
if (_startupItem.Checked)
key.DeleteValue(AppName, throwOnMissingValue: false);
else if (Environment.ProcessPath is { } exe)
key.SetValue(AppName, $"\"{exe}\"", RegistryValueKind.String);
}
catch (Exception ex) when (ex is UnauthorizedAccessException or System.Security.SecurityException or IOException)
{
// Leave the checkmark reflecting the actual registry state below.
}
_startupItem.Checked = IsStartupEnabled();
}
private static void OpenTaskManager()
{
try { Process.Start(new ProcessStartInfo("taskmgr.exe") { UseShellExecute = true })?.Dispose(); }
catch (System.ComponentModel.Win32Exception) { /* e.g. UAC prompt cancelled */ }
}
// ---------------------------------------------------------------- shutdown
// Exit: stop work and hide the overlay now. Disposal happens in Dispose(), after the
// message loop ends (Main wraps the context in `using`), so the menu is never
// disposed while its own Click handler is still running.
protected override void ExitThreadCore()
{
_stopping = true;
_timer.Stop();
if (!_overlay.IsDisposed && _overlay.Visible) _overlay.Hide();
base.ExitThreadCore();
}
protected override void Dispose(bool disposing)
{
if (disposing && !_disposed)
{
_disposed = true;
_stopping = true;
_timer.Stop();
_timer.Dispose();
SystemEvents.UserPreferenceChanged -= OnUserPreferenceChanged;
_toolTip.Dispose();
_overlay.Dispose();
_menu.Dispose();
}
base.Dispose(disposing);
}
}
/// <summary>
/// Borderless, non-activating, topmost per-pixel-alpha window drawn over the taskbar,
/// immediately left of the notification area. Content is pushed with UpdateLayeredWindow.
/// </summary>
internal sealed class OverlayForm : Form
{
private static readonly Color Background = Color.FromArgb(1, 0, 0, 0); // alpha 1: invisible but still hit-testable
private static readonly Color HotColor = Color.FromArgb(0xE8, 0x3B, 0x3B);
private const int HotThreshold = 85;
private readonly StringFormat _format;
private Font? _font;
private uint _metricsDpi;
private int _textWidth, _lineHeight; // widest case ("CPU 100%" / "RAM 100%") at _metricsDpi
private Bitmap? _bitmap;
public OverlayForm()
{
FormBorderStyle = FormBorderStyle.None;
ShowInTaskbar = false;
TopMost = true;
StartPosition = FormStartPosition.Manual;
Text = "Pulsebar";
_format = (StringFormat)StringFormat.GenericTypographic.Clone();
_format.FormatFlags |= StringFormatFlags.MeasureTrailingSpaces | StringFormatFlags.NoWrap | StringFormatFlags.NoClip;
}
protected override CreateParams CreateParams
{
get
{
CreateParams cp = base.CreateParams;
cp.ExStyle |= Native.WS_EX_LAYERED | Native.WS_EX_TOOLWINDOW | Native.WS_EX_NOACTIVATE | Native.WS_EX_TOPMOST;
return cp;
}
}
protected override bool ShowWithoutActivation => true;
/// <summary>Positions, renders and shows (or hides) the overlay. Called once per second.</summary>
public void UpdateDisplay(int cpu, int ram, Color textColor, bool menuOpen)
{
if (IsDisposed) return;
IntPtr hwnd = Handle; // forces handle creation on first call
if (!TryGetTaskbar(hwnd, out IntPtr taskbar, out Native.RECT tb))
{
if (Visible) Hide();
return;
}
uint dpi = Native.GetDpiForWindow(hwnd);
if (dpi == 0) dpi = 96;
float scale = dpi / 96f;
Font font = EnsureMetrics(dpi);
int padX = (int)Math.Round(4 * scale); // per side: ~8px * scale in total
int tbHeight = tb.Bottom - tb.Top;
int width = _textWidth + 2 * padX;
int height = Math.Max(tbHeight, 2 * _lineHeight + (int)Math.Round(4 * scale));
// Right edge: just left of the notification area; fallback to a fixed offset from the right.
int right;
IntPtr tray = Native.FindWindowEx(taskbar, IntPtr.Zero, "TrayNotifyWnd", null);
if (tray != IntPtr.Zero && Native.GetWindowRect(tray, out Native.RECT tr) &&
tr.Right - tr.Left > 0 && tr.Left > tb.Left && tr.Left <= tb.Right)
right = tr.Left - (int)Math.Round(4 * scale);
else
right = tb.Right - (int)Math.Round(220 * scale);
int x = Math.Max(tb.Left, right - width);
int y = tb.Top + (tbHeight - height) / 2;
var bounds = new Rectangle(x, y, width, height);
if (!Render(hwnd, bounds, font, padX, cpu, ram, textColor)) return;
bool wasHidden = !Visible;
if (wasHidden) Show(); // SW_SHOWNOACTIVATE (ShowWithoutActivation)
// Clicking the taskbar raises it above us; re-raise only when that happened (or we just
// appeared), so we don't fight our own menu/tooltip or other topmost windows every tick.
bool raise = !menuOpen && (wasHidden || IsBelow(hwnd, taskbar));
uint flags = Native.SWP_NOACTIVATE | Native.SWP_SHOWWINDOW | (raise ? 0u : Native.SWP_NOZORDER);
Native.SetWindowPos(hwnd, Native.HWND_TOPMOST, bounds.X, bounds.Y, bounds.Width, bounds.Height, flags);
}
// ---------------------------------------------------------------- placement
/// <summary>
/// Finds the primary taskbar and returns false when the overlay should be hidden:
/// taskbar missing, not at the bottom, auto-hidden/off-screen, or a fullscreen app in front.
/// </summary>
private static bool TryGetTaskbar(IntPtr self, out IntPtr taskbar, out Native.RECT tb)
{
tb = default;
taskbar = Native.FindWindow("Shell_TrayWnd", null);
if (taskbar == IntPtr.Zero || !Native.GetWindowRect(taskbar, out tb)) return false;
Screen? primary = Screen.PrimaryScreen;
if (primary is null) return false;
Rectangle scr = primary.Bounds;
if (tb.Bottom - tb.Top <= 0 || tb.Right - tb.Left <= 0) return false;
// Auto-hidden (slid down, leaving ~2px) or mid-animation off the bottom edge.
if (tb.Top >= scr.Bottom - 2 || tb.Bottom > scr.Bottom + 2) return false;
// Bottom taskbar only (Windows 11 default).
bool atBottom = tb.Bottom >= scr.Bottom - 2 && tb.Top > scr.Top + scr.Height / 2;
if (!atBottom) return false;
return !IsFullscreenForeground(self, taskbar, scr);
}
private static bool IsFullscreenForeground(IntPtr self, IntPtr taskbar, Rectangle screen)
{
IntPtr fg = Native.GetForegroundWindow();
if (fg == IntPtr.Zero || fg == taskbar || fg == self) return false;
var sb = new StringBuilder(256);
if (Native.GetClassName(fg, sb, sb.Capacity) > 0)
{
string cls = sb.ToString();
if (cls is "Progman" or "WorkerW" or "Shell_TrayWnd") return false; // desktop / taskbar
}
if (!Native.GetWindowRect(fg, out Native.RECT r)) return false;
return r.Left == screen.Left && r.Top == screen.Top && r.Right == screen.Right && r.Bottom == screen.Bottom;
}
/// <summary>True when the taskbar sits above us in the z-order (walks up from our window; the topmost band is short).</summary>
private static bool IsBelow(IntPtr self, IntPtr taskbar)
{
int guard = 0;
for (IntPtr h = Native.GetWindow(self, Native.GW_HWNDPREV);
h != IntPtr.Zero && guard < 1024;
h = Native.GetWindow(h, Native.GW_HWNDPREV), guard++)
{
if (h == taskbar) return true;
}
return false;
}
// ---------------------------------------------------------------- rendering
/// <summary>Creates the font and measures the widest text once per DPI.</summary>
private Font EnsureMetrics(uint dpi)
{
if (_font is not null && _metricsDpi == dpi) return _font;
_font?.Dispose();
// Segoe UI 9pt, like the Windows 11 clock: pixel size = 9 * dpi / 72.
var font = new Font("Segoe UI", 9f * dpi / 72f, FontStyle.Regular, GraphicsUnit.Pixel);
_font = font;
_metricsDpi = dpi;
using var probe = new Bitmap(1, 1, PixelFormat.Format32bppArgb);
using var g = Graphics.FromImage(probe);
g.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;
float w1 = g.MeasureString("CPU 100%", font, PointF.Empty, _format).Width;
float w2 = g.MeasureString("RAM 100%", font, PointF.Empty, _format).Width;
_textWidth = (int)Math.Ceiling(Math.Max(w1, w2)) + 1;
_lineHeight = (int)Math.Ceiling(font.GetHeight(g));
return font;
}
private bool Render(IntPtr hwnd, Rectangle bounds, Font font, int padX, int cpu, int ram, Color textColor)
{
int w = bounds.Width, h = bounds.Height;
if (w <= 0 || h <= 0) return false;
if (_bitmap is null || _bitmap.Width != w || _bitmap.Height != h)
{
_bitmap?.Dispose();
_bitmap = new Bitmap(w, h, PixelFormat.Format32bppArgb);
}
Bitmap bmp = _bitmap;
using (var g = Graphics.FromImage(bmp))
using (var textBrush = new SolidBrush(textColor))
using (var hotBrush = new SolidBrush(HotColor))
{
g.Clear(Background);
g.TextRenderingHint = TextRenderingHint.AntiAliasGridFit; // ClearType looks bad on alpha
float right = w - padX;
float top = (h - 2 * _lineHeight) / 2f;
DrawLine(g, font, "CPU ", cpu, right, top, textBrush, hotBrush);
DrawLine(g, font, "RAM ", ram, right, top + _lineHeight, textBrush, hotBrush);
}
IntPtr screenDc = Native.GetDC(IntPtr.Zero);
if (screenDc == IntPtr.Zero) return false;
IntPtr memDc = IntPtr.Zero, hBitmap = IntPtr.Zero, oldBitmap = IntPtr.Zero;
try
{
memDc = Native.CreateCompatibleDC(screenDc);
if (memDc == IntPtr.Zero) return false;
hBitmap = bmp.GetHbitmap(Color.FromArgb(0)); // 32bpp DIB, alpha preserved (premultiplied)
oldBitmap = Native.SelectObject(memDc, hBitmap);
var dst = new Native.POINT { X = bounds.X, Y = bounds.Y };
var size = new Native.SIZE { cx = w, cy = h };
var src = new Native.POINT { X = 0, Y = 0 };
var blend = new Native.BLENDFUNCTION
{
BlendOp = Native.AC_SRC_OVER,
BlendFlags = 0,
SourceConstantAlpha = 255,
AlphaFormat = Native.AC_SRC_ALPHA,
};
return Native.UpdateLayeredWindow(hwnd, screenDc, ref dst, ref size, memDc, ref src, 0, ref blend, Native.ULW_ALPHA);
}
catch (ExternalException)
{
return false; // GDI+ failure (e.g. out of handles during a session switch): skip this frame
}
finally
{
if (memDc != IntPtr.Zero)
{
if (oldBitmap != IntPtr.Zero) Native.SelectObject(memDc, oldBitmap);
Native.DeleteDC(memDc);
}
if (hBitmap != IntPtr.Zero) Native.DeleteObject(hBitmap);
Native.ReleaseDC(IntPtr.Zero, screenDc);
}
}
/// <summary>Draws "LABEL nn%" right-aligned at <paramref name="right"/>; the number turns red at 85%+.</summary>
private void DrawLine(Graphics g, Font font, string label, int value, float right, float y, Brush textBrush, Brush hotBrush)
{
string number = value.ToString(CultureInfo.InvariantCulture) + "%";
float numberWidth = g.MeasureString(number, font, PointF.Empty, _format).Width;
float labelWidth = g.MeasureString(label, font, PointF.Empty, _format).Width;
float numberX = MathF.Round(right - numberWidth);
float yy = MathF.Round(y);
g.DrawString(label, font, textBrush, numberX - labelWidth, yy, _format);
g.DrawString(number, font, value >= HotThreshold ? hotBrush : textBrush, numberX, yy, _format);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
_font?.Dispose();
_font = null;
_bitmap?.Dispose();
_bitmap = null;
_format.Dispose();
}
base.Dispose(disposing);
}
}
/// <summary>Win32 P/Invoke declarations.</summary>
internal static class Native
{
internal const int WS_EX_TOPMOST = 0x00000008;
internal const int WS_EX_TOOLWINDOW = 0x00000080;
internal const int WS_EX_LAYERED = 0x00080000;
internal const int WS_EX_NOACTIVATE = 0x08000000;
internal static readonly IntPtr HWND_TOPMOST = new(-1);
internal const uint SWP_NOZORDER = 0x0004;
internal const uint SWP_NOACTIVATE = 0x0010;
internal const uint SWP_SHOWWINDOW = 0x0040;
internal const uint GW_HWNDPREV = 3;
internal const byte AC_SRC_OVER = 0x00;
internal const byte AC_SRC_ALPHA = 0x01;
internal const int ULW_ALPHA = 0x00000002;
[StructLayout(LayoutKind.Sequential)]
internal struct FILETIME
{
public uint dwLowDateTime;
public uint dwHighDateTime;
public readonly long ToLong() => ((long)dwHighDateTime << 32) | dwLowDateTime;
}
[StructLayout(LayoutKind.Sequential)]
internal struct MEMORYSTATUSEX
{
public uint dwLength;
public uint dwMemoryLoad;
public ulong ullTotalPhys;
public ulong ullAvailPhys;
public ulong ullTotalPageFile;
public ulong ullAvailPageFile;
public ulong ullTotalVirtual;
public ulong ullAvailVirtual;
public ulong ullAvailExtendedVirtual;
}
[StructLayout(LayoutKind.Sequential)]
internal struct RECT
{
public int Left;
public int Top;
public int Right;
public int Bottom;
}
[StructLayout(LayoutKind.Sequential)]
internal struct POINT
{
public int X;
public int Y;
}
[StructLayout(LayoutKind.Sequential)]
internal struct SIZE
{
public int cx;
public int cy;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
internal struct BLENDFUNCTION
{
public byte BlendOp;
public byte BlendFlags;
public byte SourceConstantAlpha;
public byte AlphaFormat;
}
// ---- kernel32
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool GetSystemTimes(out FILETIME idleTime, out FILETIME kernelTime, out FILETIME userTime);
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool GlobalMemoryStatusEx(ref MEMORYSTATUSEX buffer);
// ---- user32
[DllImport("user32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
internal static extern IntPtr FindWindow(string lpClassName, string? lpWindowName);
[DllImport("user32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
internal static extern IntPtr FindWindowEx(IntPtr hWndParent, IntPtr hWndChildAfter, string lpszClass, string? lpszWindow);
[DllImport("user32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool GetWindowRect(IntPtr hWnd, out RECT lpRect);
[DllImport("user32.dll")]
internal static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool SetForegroundWindow(IntPtr hWnd);
[DllImport("user32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
internal static extern int GetClassName(IntPtr hWnd, StringBuilder lpClassName, int nMaxCount);
[DllImport("user32.dll", SetLastError = true)]
internal static extern IntPtr GetWindow(IntPtr hWnd, uint uCmd);
[DllImport("user32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags);
[DllImport("user32.dll")]
internal static extern uint GetDpiForWindow(IntPtr hwnd);
[DllImport("user32.dll")]
internal static extern IntPtr GetDC(IntPtr hWnd);
[DllImport("user32.dll")]
internal static extern int ReleaseDC(IntPtr hWnd, IntPtr hDC);
[DllImport("user32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool UpdateLayeredWindow(IntPtr hwnd, IntPtr hdcDst, ref POINT pptDst, ref SIZE psize,
IntPtr hdcSrc, ref POINT pptSrc, int crKey, ref BLENDFUNCTION pblend, int dwFlags);
// ---- gdi32
[DllImport("gdi32.dll", SetLastError = true)]
internal static extern IntPtr CreateCompatibleDC(IntPtr hdc);
[DllImport("gdi32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool DeleteDC(IntPtr hdc);
[DllImport("gdi32.dll")]
internal static extern IntPtr SelectObject(IntPtr hdc, IntPtr hgdiobj);
[DllImport("gdi32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool DeleteObject(IntPtr hObject);
}