using System.Drawing.Drawing2D; using System.Runtime.InteropServices; namespace UCVL.VPNPlus; /// /// Draws the caption as part of the existing header, without replacing Win32's /// move/size/system-command implementation or any application close logic. /// Native sizing/system commands remain, but WS_CAPTION must never be present: /// there is exactly one owner for the caption buttons, in the client area. /// internal sealed class WindowChrome : IDisposable { internal const int CaptionHeight = 30; private readonly Form _form; private readonly Panel _header; private readonly Action _requestExit; private readonly ToolTip _toolTip = new(); private readonly ChromeFormWindow _window; private readonly Dictionary _children = new(); private bool _disposed; private bool _minimizePending; private int _handleGeneration; private int _modeGeneration; internal string LastMinMaxForTest { get; private set; } = "none"; internal bool LoginMode { get; private set; } internal CaptionButton MinimizeButton { get; } = new(CaptionAction.Minimize); internal WindowChrome(Form form, Panel header, Action requestExit) { _form = form; _header = header; _requestExit = requestExit; _window = new ChromeFormWindow(this); // Managed geometry must see a client-only form. Leaving Sizable here // makes WinForms add the removed caption dimensions again on restore. // Actual HWND styles below still retain native move/resize/system menu. form.FormBorderStyle = FormBorderStyle.None; form.MinimizeBox = true; form.MaximizeBox = false; form.ControlBox = true; MinimizeButton.TabIndex = 900; MinimizeButton.Click += CaptionClicked; header.Controls.Add(MinimizeButton); form.HandleCreated += FormHandleCreated; form.HandleDestroyed += FormHandleDestroyed; form.SizeChanged += FormSizeChanged; form.DpiChanged += FormDpiChanged; form.Disposed += FormDisposed; header.SizeChanged += HeaderSizeChanged; TrackChildren(form); LayoutButtons(); if (form.IsHandleCreated) AttachForm(); } internal void SetLoginMode(bool loginMode) { if (_disposed || LoginMode == loginMode) return; LoginMode = loginMode; // Invalidate even a dashboard -> login -> dashboard round trip. An old // posted click must not minimize the new view or clear its pending click. _modeGeneration++; _minimizePending = false; MinimizeButton.Action = loginMode ? CaptionAction.Close : CaptionAction.Minimize; LayoutButtons(); } private void CaptionClicked(object? sender, EventArgs e) { if (_disposed || _form.IsDisposed || _form.Disposing || !_form.IsHandleCreated) return; if (LoginMode) { _requestExit(); return; } if (_minimizePending) return; // Button.Click runs inside MouseUp while the button still owns capture. // The native SC_MINIMIZE path can do nothing there. Queue the state // change after MouseUp releases capture, including for keyboard clicks. _minimizePending = true; var generation = _handleGeneration; var modeGeneration = _modeGeneration; try { _form.BeginInvoke(() => { if (generation != _handleGeneration || modeGeneration != _modeGeneration) return; _minimizePending = false; if (LoginMode || _disposed || _form.IsDisposed || _form.Disposing || !_form.IsHandleCreated) return; _form.WindowState = FormWindowState.Minimized; }); } catch (InvalidOperationException) { if (generation == _handleGeneration && modeGeneration == _modeGeneration) _minimizePending = false; } } private void FormHandleCreated(object? sender, EventArgs e) => AttachForm(); private void FormHandleDestroyed(object? sender, EventArgs e) { // A posted callback may be lost or survive handle recreation. Neither // case should block a new click or minimize a newly created window. _handleGeneration++; _minimizePending = false; _window.ReleaseHandle(); } private void FormSizeChanged(object? sender, EventArgs e) => LayoutButtons(); private void FormDpiChanged(object? sender, DpiChangedEventArgs e) => LayoutButtons(); private void HeaderSizeChanged(object? sender, EventArgs e) => LayoutButtons(); private void FormDisposed(object? sender, EventArgs e) => Dispose(); private void AttachForm() { if (_disposed) return; _window.AssignHandle(_form.Handle); DisableNativeFrameRendering(); var style = ChromeNative.GetWindowLongPtr(_form.Handle, ChromeNative.GwlStyle).ToInt64(); ChromeNative.SetWindowLongPtr(_form.Handle, ChromeNative.GwlStyle, (IntPtr)ChromeNative.ClientChromeStyle(style)); var menu = ChromeNative.GetSystemMenu(_form.Handle, false); if (menu != IntPtr.Zero) { ChromeNative.DeleteMenu(menu, ChromeNative.ScMaximize, 0); ChromeNative.DeleteMenu(menu, ChromeNative.ScClose, 0); ChromeNative.DeleteMenu(menu, ChromeNative.ScExplicitExit, 0); ChromeNative.AppendMenu(menu, 0, ChromeNative.ScExplicitExit, "断开并退出"); } // Microsoft custom-frame contract: recalculate the old native frame // after attaching WM_NCCALCSIZE. No top-only patch/white overlay. ChromeNative.SetWindowPos(_form.Handle, IntPtr.Zero, 0, 0, 0, 0, ChromeNative.SwpFrameChanged | ChromeNative.SwpNoMove | ChromeNative.SwpNoSize | ChromeNative.SwpNoZOrder | ChromeNative.SwpNoActivate); LayoutButtons(); } private void DisableNativeFrameRendering() { // Keep native sizing/system commands, but give this client-drawn frame // one paint owner. NCCALCSIZE alone does not disable DWM caption paint. // WM_NCPAINT/WM_NCACTIVATE below also cover classic/noncomposited frames. var policy = 1; // DWMNCRP_DISABLED (2 is ENABLED). _ = ChromeNative.DwmSetWindowAttribute(_form.Handle, 2 /* DWMWA_NCRENDERING_POLICY */, ref policy, sizeof(int)); } private int Scale(int logical) => Math.Max(1, (int)Math.Round(logical * _form.DeviceDpi / 96.0)); internal void LayoutButtons() { if (_disposed || _header.IsDisposed) return; var width = Scale(46); var height = Scale(CaptionHeight); var maximized = _form.WindowState == FormWindowState.Maximized; // Keep the entire clickable button clear of the native resize band. // Maximized windows have no resize band and use the screen edge again. var inset = maximized ? 0 : Scale(6); MinimizeButton.Bounds = new Rectangle(Math.Max(0, _header.ClientSize.Width - width - inset), inset, width, height); _toolTip.SetToolTip(MinimizeButton, MinimizeButton.AccessibleName); MinimizeButton.BringToFront(); MinimizeButton.Invalidate(); } private void TrackChildren(Control parent) { parent.ControlAdded += ChildAdded; parent.ControlRemoved += ChildRemoved; foreach (Control child in parent.Controls) TrackChild(child); } private void ChildAdded(object? sender, ControlEventArgs e) { if (e.Control is { } child) TrackChild(child); } private void ChildRemoved(object? sender, ControlEventArgs e) { if (e.Control is { } child) UntrackChild(child); } private void TrackChild(Control child) { if (_disposed || _children.ContainsKey(child)) return; _children.Add(child, new ChromeChildWindow(this, child)); TrackChildren(child); } private void UntrackChild(Control child) { foreach (Control nested in child.Controls) UntrackChild(nested); child.ControlAdded -= ChildAdded; child.ControlRemoved -= ChildRemoved; if (_children.Remove(child, out var window)) window.Dispose(); } internal int HitTest(Point screenPoint) { var location = _form.PointToClient(screenPoint); var border = ChromeGeometry.ResizeHitTest(_form.ClientSize, location, Scale(6), _form.WindowState != FormWindowState.Maximized); if (border != ChromeNative.HtClient) return border; var headerPoint = _header.PointToClient(screenPoint); if (!_header.Visible || !_header.ClientRectangle.Contains(headerPoint)) return ChromeNative.HtClient; // Only known decorative controls are a drag surface. A future ComboBox, // button, link, editable text, or custom interactive control stays client. Control surface = _header; while (surface.GetChildAtPoint(surface.PointToClient(screenPoint), GetChildAtPointSkip.Invisible) is { } child) { if (!IsDecorative(child)) return ChromeNative.HtClient; surface = child; } return ChromeNative.HtCaption; } internal static bool IsDecorative(Control control) => control switch { LinkLabel => false, Label label => !label.TabStop && label.ContextMenuStrip is null, PictureBox picture => !picture.TabStop && picture.ContextMenuStrip is null, Panel panel => !panel.TabStop && panel.ContextMenuStrip is null, _ => false }; internal Rectangle HeaderScreenBounds => _header.RectangleToScreen(_header.ClientRectangle); public void Dispose() { if (_disposed) return; _disposed = true; _form.HandleCreated -= FormHandleCreated; _form.HandleDestroyed -= FormHandleDestroyed; _form.SizeChanged -= FormSizeChanged; _form.DpiChanged -= FormDpiChanged; _form.Disposed -= FormDisposed; _form.ControlAdded -= ChildAdded; _form.ControlRemoved -= ChildRemoved; _header.SizeChanged -= HeaderSizeChanged; foreach (var item in _children) { item.Key.ControlAdded -= ChildAdded; item.Key.ControlRemoved -= ChildRemoved; item.Value.Dispose(); } _children.Clear(); _window.ReleaseHandle(); _toolTip.Dispose(); } private sealed class ChromeFormWindow(WindowChrome owner) : NativeWindow { protected override void WndProc(ref Message m) { if (m.Msg == ChromeNative.WmSysCommand) { var command = (int)(m.WParam.ToInt64() & 0xfff0); if (command == ChromeNative.ScClose) { if (owner.LoginMode) owner._requestExit(); m.Result = IntPtr.Zero; return; } if (command == ChromeNative.ScMaximize) { m.Result = IntPtr.Zero; return; } if (command == ChromeNative.ScExplicitExit) { owner._requestExit(); m.Result = IntPtr.Zero; return; } } if (m.Msg == ChromeNative.WmNcLButtonDoubleClick && m.WParam.ToInt64() == ChromeNative.HtCaption) { m.Result = IntPtr.Zero; return; } if (m.Msg == ChromeNative.WmNcPaint) { m.Result = IntPtr.Zero; return; } if (m.Msg == ChromeNative.WmNcActivate) { // -1 preserves activation processing without asking DefWindowProc // to draw another set of caption buttons over the header. m.LParam = (IntPtr)(-1); base.WndProc(ref m); return; } if (m.Msg is ChromeNative.WmDwmCompositionChanged or ChromeNative.WmThemeChanged) { base.WndProc(ref m); owner.DisableNativeFrameRendering(); owner._header.Invalidate(true); return; } if (m.Msg == ChromeNative.WmStyleChanging && m.WParam.ToInt64() == ChromeNative.GwlStyle) { // WinForms may refresh styles on activation/show/state change. // Never let a managed style refresh reinstate a second caption. // Keep native sizing/system commands, not native title buttons. base.WndProc(ref m); var styles = Marshal.PtrToStructure(m.LParam); styles.NewStyle = (uint)ChromeNative.ClientChromeStyle(styles.NewStyle); Marshal.StructureToPtr(styles, m.LParam, false); return; } if (m.Msg == ChromeNative.WmNcCalcSize) { // Whole window = whole client canvas. Header paints from y=0, // including the caption area, with one uninterrupted background. if (ChromeNative.IsZoomed(Handle) && m.LParam != IntPtr.Zero) { // Windows puts a maximized thick frame outside the monitor's // work area. Keep that native invisible frame, but explicitly // constrain the client canvas so no button is off-screen and // the content never covers the taskbar. The first RECT exists // for both NCCALCSIZE message forms. var monitor = ChromeNative.MonitorFromWindow(Handle, 2); var info = new ChromeNative.MonitorInfo { Size = Marshal.SizeOf() }; if (ChromeNative.GetMonitorInfo(monitor, ref info)) Marshal.StructureToPtr(info.Work, m.LParam, false); } m.Result = IntPtr.Zero; return; } if (m.Msg == ChromeNative.WmNcHitTest) { // There are no standard DWM caption buttons to ask DwmDefWindowProc // about. Our real WinForms buttons must remain ordinary HTCLIENT. m.Result = (IntPtr)owner.HitTest(ChromeGeometry.ScreenPoint(m.LParam)); return; } if (m.Msg == ChromeNative.WmGetMinMaxInfo) { base.WndProc(ref m); if (m.LParam != IntPtr.Zero) { var monitor = ChromeNative.MonitorFromWindow(Handle, 2); var info = new ChromeNative.MonitorInfo { Size = Marshal.SizeOf() }; if (ChromeNative.GetMonitorInfo(monitor, ref info)) { var bounds = ChromeGeometry.MaximizedBounds(info.Monitor.ToRectangle(), info.Work.ToRectangle()); var sizes = Marshal.PtrToStructure(m.LParam); sizes.MaxPosition = new ChromeNative.NativePoint(bounds.Location); sizes.MaxSize = new ChromeNative.NativePoint(bounds.Size.Width, bounds.Size.Height); // Base WinForms preserves MinimumSize/MaximumSize tracking // limits; do not clamp max track size to one monitor. Marshal.StructureToPtr(sizes, m.LParam, false); owner.LastMinMaxForTest = $"monitor={info.Monitor.ToRectangle()}; work={info.Work.ToRectangle()}; max={bounds}"; } } return; } base.WndProc(ref m); } } private sealed class ChromeChildWindow : NativeWindow, IDisposable { private readonly WindowChrome _owner; private readonly Control _control; internal ChromeChildWindow(WindowChrome owner, Control control) { _owner = owner; _control = control; control.HandleCreated += Created; control.HandleDestroyed += Destroyed; if (control.IsHandleCreated) AssignHandle(control.Handle); } private void Created(object? sender, EventArgs e) => AssignHandle(_control.Handle); private void Destroyed(object? sender, EventArgs e) => ReleaseHandle(); protected override void WndProc(ref Message m) { if (m.Msg == ChromeNative.WmNcHitTest) { var result = _owner.HitTest(ChromeGeometry.ScreenPoint(m.LParam)); if (result != ChromeNative.HtClient) { // Hit-testing starts at the child HWND. Passing decorative // header/edge hits through to the parent is necessary for // real OS dragging and all eight resize edges/corners. m.Result = (IntPtr)ChromeNative.HtTransparent; return; } } base.WndProc(ref m); } public void Dispose() { _control.HandleCreated -= Created; _control.HandleDestroyed -= Destroyed; ReleaseHandle(); } } } internal enum CaptionAction { Minimize, Maximize, Close } internal sealed class CaptionButton : Button { private CaptionAction _action; private bool _hot, _pressed; internal bool RestoreGlyph { get; set; } internal CaptionAction Action { get => _action; set { var changed = _action != value; var releaseCapture = changed && IsHandleCreated && Capture; _action = value; AccessibleName = value switch { CaptionAction.Close => "退出软件", CaptionAction.Maximize => "最大化", _ => "最小化" }; if (changed) { // Do not turn a held minimize gesture into a login exit. // Releasing capture also clears ButtonBase's pressed state. // Commit the new action first: capture-change handlers may // synchronously select a newer mode and must remain its owner. _hot = _pressed = false; } if (releaseCapture) Capture = false; Invalidate(); } } internal CaptionButton(CaptionAction action) { Action = action; SetStyle(ControlStyles.UserPaint | ControlStyles.SupportsTransparentBackColor | ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer, true); BackColor = Color.Transparent; ForeColor = Brand.Navy; UseVisualStyleBackColor = false; FlatStyle = FlatStyle.Flat; FlatAppearance.BorderSize = 0; FlatAppearance.MouseOverBackColor = Color.Transparent; FlatAppearance.MouseDownBackColor = Color.Transparent; TabStop = true; AccessibleRole = AccessibleRole.PushButton; Cursor = Cursors.Default; // ButtonBase defaults to Opaque and paints its background in OnPaint. // Our glyph-only OnPaint needs the separate background layer to run. SetStyle(ControlStyles.Opaque, false); } protected override void OnMouseEnter(EventArgs e) { _hot = true; Invalidate(); base.OnMouseEnter(e); } protected override void OnMouseLeave(EventArgs e) { _hot = _pressed = false; Invalidate(); base.OnMouseLeave(e); } protected override void OnMouseDown(MouseEventArgs e) { _pressed = e.Button == MouseButtons.Left; Invalidate(); base.OnMouseDown(e); } protected override void OnMouseUp(MouseEventArgs e) { _pressed = false; Invalidate(); base.OnMouseUp(e); } protected override void OnMouseCaptureChanged(EventArgs e) { if (!Capture) { _pressed = false; Invalidate(); } base.OnMouseCaptureChanged(e); } protected override void OnGotFocus(EventArgs e) { Invalidate(); base.OnGotFocus(e); } protected override void OnLostFocus(EventArgs e) { Invalidate(); base.OnLostFocus(e); } protected override void OnPaintBackground(PaintEventArgs e) { if (Parent is not { } parent) { base.OnPaintBackground(e); return; } // Repaint the actual header beneath this button on EVERY paint. Do not // let ButtonBase's themed/flat background reuse a previous glyph or an // alpha-blended hover tile. InvokePaint does not render child controls. var state = e.Graphics.Save(); try { e.Graphics.TranslateTransform(-Left, -Top); if (parent is BrandHeaderPanel) { // Paint decoration directly, never ask a native themed Button // or sibling control to reconstruct the transparent backdrop. ScenicTheme.Backdrop(e.Graphics, parent.ClientSize, parent.DeviceDpi, header: true); return; } using var background = new PaintEventArgs(e.Graphics, Bounds); InvokePaintBackground(parent, background); InvokePaint(parent, background); } finally { e.Graphics.Restore(state); } } protected override void OnPaint(PaintEventArgs e) { // OnPaintBackground invokes the parent's painting at the translated // coordinates; only glyph/highlight is drawn here, never a white tile. if (_hot || _pressed) { using var fill = new SolidBrush(_action == CaptionAction.Close ? Color.FromArgb(_pressed ? 230 : 210, 196, 49, 64) : Color.FromArgb(_pressed ? 62 : 32, 18, 105, 175)); e.Graphics.FillRectangle(fill, ClientRectangle); } var scale = DeviceDpi / 96f; var size = Math.Max(9, (int)Math.Round(10 * scale)); var left = (Width - size) / 2f; var top = (Height - size) / 2f; var foreground = _action == CaptionAction.Close && (_hot || _pressed) ? Color.White : ForeColor; using var pen = new Pen(foreground, Math.Max(1.2f, 1.3f * scale)); e.Graphics.SmoothingMode = SmoothingMode.AntiAlias; switch (_action) { case CaptionAction.Minimize: e.Graphics.DrawLine(pen, left, top + size / 2f, left + size, top + size / 2f); break; case CaptionAction.Maximize when RestoreGlyph: var shift = Math.Max(2, (int)Math.Round(3 * scale)); e.Graphics.DrawLines(pen, new PointF[] { new(left + shift, top + shift), new(left + shift, top), new(left + size, top), new(left + size, top + size - shift), new(left + size - shift, top + size - shift) }); e.Graphics.DrawRectangle(pen, left, top + shift, size - shift, size - shift); break; case CaptionAction.Maximize: e.Graphics.DrawRectangle(pen, left, top, size, size); break; case CaptionAction.Close: e.Graphics.DrawLine(pen, left, top, left + size, top + size); e.Graphics.DrawLine(pen, left + size, top, left, top + size); break; } if (Focused && ShowFocusCues) ControlPaint.DrawFocusRectangle(e.Graphics, Rectangle.Inflate(ClientRectangle, -4, -4), foreground, BackColor); } } internal static class ChromeGeometry { internal static Point ScreenPoint(IntPtr parameter) { var raw = parameter.ToInt64(); // GET_X/Y_LPARAM must be signed; LOWORD/HIWORD breaks left/top monitors. return new Point(unchecked((short)(raw & 0xffff)), unchecked((short)((raw >> 16) & 0xffff))); } internal static Rectangle MaximizedBounds(Rectangle monitor, Rectangle work) => new(work.Left - monitor.Left, work.Top - monitor.Top, work.Width, work.Height); internal static int ResizeHitTest(Size size, Point point, int border, bool resizable) { if (!resizable || point.X < 0 || point.Y < 0 || point.X >= size.Width || point.Y >= size.Height) return ChromeNative.HtClient; var left = point.X < border; var right = point.X >= size.Width - border; var top = point.Y < border; var bottom = point.Y >= size.Height - border; if (top) return left ? 13 : right ? 14 : 12; if (bottom) return left ? 16 : right ? 17 : 15; return left ? 10 : right ? 11 : ChromeNative.HtClient; } } internal static class ChromeNative { internal const int WmNcCalcSize = 0x83, WmNcHitTest = 0x84, WmGetMinMaxInfo = 0x24; internal const int WmNcPaint = 0x85, WmNcActivate = 0x86; internal const int WmDwmCompositionChanged = 0x31e, WmThemeChanged = 0x31a; internal const int WmSysCommand = 0x112; internal const int WmNcLButtonDoubleClick = 0xa3; internal const int WmStyleChanging = 0x7c, GwlStyle = -16; internal const uint WsCaption = 0x00c00000; internal const uint WsMaximizeBox = 0x00010000; internal const uint NativeFrameStyles = 0x00040000 | 0x00080000 | 0x00020000; internal static long ClientChromeStyle(long style) => (style & ~((long)WsCaption | WsMaximizeBox)) | NativeFrameStyles; internal const int HtClient = 1, HtCaption = 2, HtTransparent = -1; internal const int ScMinimize = 0xf020, ScMaximize = 0xf030, ScRestore = 0xf120, ScClose = 0xf060; internal const int ScExplicitExit = 0x1000; internal const uint SwpNoSize = 1, SwpNoMove = 2, SwpNoZOrder = 4, SwpNoActivate = 0x10, SwpFrameChanged = 0x20; [StructLayout(LayoutKind.Sequential)] internal struct NativePoint { internal int X, Y; internal NativePoint(int x, int y) { X = x; Y = y; } internal NativePoint(Point p) : this(p.X, p.Y) { } } [StructLayout(LayoutKind.Sequential)] internal struct NativeRect { internal int Left, Top, Right, Bottom; internal Rectangle ToRectangle() => Rectangle.FromLTRB(Left, Top, Right, Bottom); } [StructLayout(LayoutKind.Sequential)] internal struct MinMaxInfo { internal NativePoint Reserved, MaxSize, MaxPosition, MinTrackSize, MaxTrackSize; } [StructLayout(LayoutKind.Sequential)] internal struct MonitorInfo { internal int Size; internal NativeRect Monitor, Work; internal uint Flags; } [StructLayout(LayoutKind.Sequential)] internal struct StyleStruct { internal uint OldStyle, NewStyle; } [DllImport("user32.dll", EntryPoint = "GetWindowLongPtrW")] internal static extern IntPtr GetWindowLongPtr(IntPtr handle, int index); [DllImport("user32.dll", EntryPoint = "SetWindowLongPtrW")] internal static extern IntPtr SetWindowLongPtr(IntPtr handle, int index, IntPtr value); [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool SetWindowPos(IntPtr handle, IntPtr after, int x, int y, int width, int height, uint flags); [DllImport("user32.dll", CharSet = CharSet.Unicode)] internal static extern IntPtr SendMessage(IntPtr handle, int message, IntPtr wParam, IntPtr lParam); [DllImport("user32.dll")] internal static extern IntPtr MonitorFromWindow(IntPtr handle, uint flags); [DllImport("user32.dll", CharSet = CharSet.Unicode)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool GetMonitorInfo(IntPtr handle, ref MonitorInfo info); [DllImport("user32.dll")] internal static extern IntPtr GetSystemMenu(IntPtr handle, [MarshalAs(UnmanagedType.Bool)] bool reset); [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool DeleteMenu(IntPtr menu, uint position, uint flags); [DllImport("user32.dll", CharSet = CharSet.Unicode)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool AppendMenu(IntPtr menu, uint flags, nuint identifier, string text); [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool IsZoomed(IntPtr handle); [DllImport("dwmapi.dll")] internal static extern int DwmSetWindowAttribute(IntPtr handle, int attribute, ref int value, int size); [DllImport("dwmapi.dll")] internal static extern int DwmGetWindowAttribute(IntPtr handle, int attribute, out int value, int size); }