Class Window
- Namespace
- SharpConsoleUI
- Assembly
- SharpConsoleUI.dll
Represents a window in the console UI system that can contain controls and handle user input. Implements IContainer for control management.
public class Window : IContainer
- Inheritance
-
Window
- Implements
- Derived
- Inherited Members
Constructors
Window(ConsoleWindowSystem, Window?)
Initializes a new instance of the Window class without a background task.
public Window(ConsoleWindowSystem windowSystem, Window? parentWindow = null)
Parameters
windowSystemConsoleWindowSystemThe console window system that manages this window.
parentWindowWindowOptional parent window for positioning and modal behavior.
Window(ConsoleWindowSystem, WindowThreadDelegateAsync, Window?)
Initializes a new instance of the Window class with an async background task.
public Window(ConsoleWindowSystem windowSystem, Window.WindowThreadDelegateAsync windowThreadMethod, Window? parentWindow = null)
Parameters
windowSystemConsoleWindowSystemThe console window system that manages this window.
windowThreadMethodWindow.WindowThreadDelegateAsyncThe async delegate to run in the background for this window.
parentWindowWindowOptional parent window for positioning and modal behavior.
Properties
ActiveBorderForegroundColor
Gets or sets the foreground color of the window border when active.
public Color ActiveBorderForegroundColor { get; set; }
Property Value
- Color
ActiveTitleForegroundColor
Gets or sets the foreground color of the window title when active.
public Color ActiveTitleForegroundColor { get; set; }
Property Value
- Color
AlwaysOnTop
Gets or sets a value indicating whether this window always renders on top of normal windows. AlwaysOnTop windows render after normal windows regardless of ZIndex.
public bool AlwaysOnTop { get; set; }
Property Value
AsyncThreadCleanupTimeout
Gets or sets the timeout for async window thread cleanup. If thread doesn't respond to cancellation within this time, window transforms to error state. Default is 5 seconds.
public TimeSpan AsyncThreadCleanupTimeout { get; set; }
Property Value
BackgroundColor
Gets or sets the background color of the window content area. If not set, uses the theme's WindowBackgroundColor (or ModalBackgroundColor for modals).
public Color BackgroundColor { get; set; }
Property Value
- Color
BorderStyle
Gets or sets the border style for this window. When set to BorderStyle.None, border areas render as spaces with window background color while preserving layout dimensions.
public BorderStyle BorderStyle { get; set; }
Property Value
ForegroundColor
Gets or sets the default foreground color for window content. If not set, uses the theme's WindowForegroundColor.
public Color ForegroundColor { get; set; }
Property Value
- Color
GetConsoleWindowSystem
Gets the console window system that manages this window.
public ConsoleWindowSystem? GetConsoleWindowSystem { get; }
Property Value
Guid
Gets the unique identifier for this window instance.
public string Guid { get; }
Property Value
Height
Gets or sets the height of the window in character rows.
public int Height { get; set; }
Property Value
InactiveBorderForegroundColor
Gets or sets the foreground color of the window border when inactive.
public Color InactiveBorderForegroundColor { get; set; }
Property Value
- Color
InactiveTitleForegroundColor
Gets or sets the foreground color of the window title when inactive.
public Color InactiveTitleForegroundColor { get; set; }
Property Value
- Color
IsClosable
Gets or sets a value indicating whether the window can be closed by the user.
public bool IsClosable { get; set; }
Property Value
IsContentVisible
Gets or sets a value indicating whether the window content is visible.
public bool IsContentVisible { get; set; }
Property Value
IsDirty
Gets or sets a value indicating whether the window needs to be redrawn. When true, the window will be rendered on the next frame update. Thread-safe using Interlocked operations.
public bool IsDirty { get; set; }
Property Value
IsDragging
Gets or sets a value indicating whether the window is currently being dragged.
public bool IsDragging { get; set; }
Property Value
IsMaximizable
Gets or sets a value indicating whether the window can be maximized.
public bool IsMaximizable { get; set; }
Property Value
IsMinimizable
Gets or sets a value indicating whether the window can be minimized.
public bool IsMinimizable { get; set; }
Property Value
IsMovable
Gets or sets a value indicating whether the window can be moved by the user.
public bool IsMovable { get; set; }
Property Value
IsResizable
Gets or sets a value indicating whether the window can be resized by the user.
public bool IsResizable { get; set; }
Property Value
IsScrollable
Gets or sets a value indicating whether the window content is scrollable.
public bool IsScrollable { get; set; }
Property Value
Left
Gets or sets the left position of the window in character columns. When set, automatically invalidates exposed regions for proper rendering.
public int Left { get; set; }
Property Value
Mode
Gets or sets the window mode (Normal or Modal).
public WindowMode Mode { get; set; }
Property Value
Name
Optional unique name for finding/identifying this window. User-defined string for singleton window patterns (e.g., "LogViewer", "Settings").
public string? Name { get; set; }
Property Value
OriginalHeight
Gets or sets the original height before maximizing, used for restore.
public int OriginalHeight { get; set; }
Property Value
OriginalLeft
Gets or sets the original left position before maximizing, used for restore.
public int OriginalLeft { get; set; }
Property Value
OriginalTop
Gets or sets the original top position before maximizing, used for restore.
public int OriginalTop { get; set; }
Property Value
OriginalWidth
Gets or sets the original width before maximizing, used for restore.
public int OriginalWidth { get; set; }
Property Value
ParentWindow
Gets the parent window if this is a subwindow, otherwise null.
public Window? ParentWindow { get; }
Property Value
RenderLock
Gets or sets a value indicating whether rendering to screen is locked. When true, the window performs all internal work (measure, layout, paint to buffer) but does not output to the render pipeline. Useful for batching multiple updates to appear atomically. When unlocked, automatically invalidates to trigger render.
public bool RenderLock { get; set; }
Property Value
Renderer
Gets the window's renderer, providing access to rendering internals.
public WindowRenderer? Renderer { get; }
Property Value
Remarks
Exposes the renderer for advanced scenarios like custom buffer effects, transitions, and compositor-style manipulations. Use the PostBufferPaint event on the renderer to safely manipulate the character buffer after painting.
RootLayoutNode
Gets the root layout node for this window.
public LayoutNode? RootLayoutNode { get; }
Property Value
ScrollOffset
Gets or sets the vertical scroll offset for window content.
public int ScrollOffset { get; set; }
Property Value
ShowCloseButton
Gets or sets a value indicating whether the close button [X] is shown in the title bar. This only affects the visual display - use IsClosable to prevent closing entirely.
public bool ShowCloseButton { get; set; }
Property Value
ShowTitle
Gets or sets whether the window title is displayed in the title bar. When false, only the border is shown without the title text.
public bool ShowTitle { get; set; }
Property Value
State
Gets or sets the current state of the window (Normal, Minimized, Maximized).
public WindowState State { get; set; }
Property Value
Tag
Gets or sets an arbitrary object value that can be attached to this window.
public object? Tag { get; set; }
Property Value
Title
Gets or sets the title displayed in the window's title bar.
public string Title { get; set; }
Property Value
Top
Gets or sets the top position of the window in character rows. When set, automatically invalidates exposed regions for proper rendering.
public int Top { get; set; }
Property Value
TotalLines
Gets the total number of content lines including sticky headers.
public int TotalLines { get; }
Property Value
UseDOMLayout
Gets whether DOM-based layout is enabled. DOM layout is always enabled and is the only rendering path.
[Obsolete("DOM layout is now always enabled. This property will be removed.")]
public bool UseDOMLayout { get; }
Property Value
Width
Gets or sets the width of the window in character columns.
public int Width { get; set; }
Property Value
ZIndex
Gets or sets the Z-order index for layering windows.
public int ZIndex { get; set; }
Property Value
Methods
AddControl(IWindowControl)
public void AddControl(IWindowControl content)
Parameters
contentIWindowControl
ClearControls()
Removes all controls from the window.
public void ClearControls()
Close(bool)
Attempts to close the window. If the window is in a system, delegates to CloseWindow() for proper cleanup.
public bool Close(bool force = false)
Parameters
forceboolIf true, forces the window to close even if IsClosable is false or OnClosing cancels.
Returns
- bool
True if the window was closed or close was initiated; false if closing was cancelled.
ContainsControl(IWindowControl)
Determines whether this window contains the specified control.
public bool ContainsControl(IWindowControl content)
Parameters
contentIWindowControlThe control to check for.
Returns
- bool
True if the control is in this window; otherwise false.
CreatePortal(IWindowControl, IWindowControl)
Creates a portal overlay for the specified control. Portal content renders on top of all normal content with no parent clipping. Portals are useful for dropdowns, tooltips, context menus, and other overlay content.
public LayoutNode? CreatePortal(IWindowControl ownerControl, IWindowControl portalContent)
Parameters
ownerControlIWindowControlThe control creating the portal.
portalContentIWindowControlThe content to render as an overlay.
Returns
- LayoutNode
The portal LayoutNode for later removal, or null if owner not found.
FindControl(string)
Finds a control by name, searching recursively through all containers.
public IWindowControl? FindControl(string name)
Parameters
namestringThe name of the control to find.
Returns
- IWindowControl
The control if found, otherwise null.
FindControl<T>(string)
Finds a control by name, searching recursively through all containers.
public T? FindControl<T>(string name) where T : class, IWindowControl
Parameters
namestringThe name of the control to find.
Returns
- T
The control if found, otherwise null.
Type Parameters
TThe type of control to find.
FocusControl(IInteractiveControl?)
Sets focus to the specified control in this window. This is the recommended way to programmatically change focus, as it properly updates Window's internal focus tracking and unfocuses the previously focused control.
public void FocusControl(IInteractiveControl? control)
Parameters
controlIInteractiveControlThe control to focus, or null to clear focus entirely.
ForceRebuildLayout()
Forces a complete rebuild of the DOM tree. Use this when the control hierarchy changes structurally (e.g., adding/removing columns in a grid) rather than just property changes. This is more expensive than Invalidate() but necessary for structural changes.
public void ForceRebuildLayout()
GetContentFromDesktopCoordinates(Point?)
Gets the control at the specified desktop coordinates.
public IWindowControl? GetContentFromDesktopCoordinates(Point? point)
Parameters
pointPoint?The desktop coordinates to check.
Returns
- IWindowControl
The control at the specified position, or null if none found.
GetControlByIndex(int)
Gets a control by its index in the controls collection.
public IWindowControl? GetControlByIndex(int index)
Parameters
indexintThe zero-based index of the control.
Returns
- IWindowControl
The control at the specified index, or null if out of range.
GetControlByTag<T>(string)
Gets a control of type T by its tag value.
public IWindowControl? GetControlByTag<T>(string tag) where T : IWindowControl
Parameters
tagstringThe tag value to match.
Returns
- IWindowControl
The first matching control, or null if not found.
Type Parameters
TThe type of control to search for.
GetControls()
Gets a copy of all controls in this window.
public List<IWindowControl> GetControls()
Returns
- List<IWindowControl>
A list containing all controls.
GetControlsByType<T>()
Gets all controls of the specified type.
public List<T> GetControlsByType<T>() where T : IWindowControl
Returns
- List<T>
A list of controls of type T.
Type Parameters
TThe type of controls to retrieve.
GetControlsCount()
Gets the number of controls in this window.
public int GetControlsCount()
Returns
- int
The control count.
GetIsActive()
Gets a value indicating whether this window is currently active.
public bool GetIsActive()
Returns
- bool
True if the window is active; otherwise false.
GetLayoutNode(IWindowControl)
Gets the LayoutNode associated with a control.
public LayoutNode? GetLayoutNode(IWindowControl control)
Parameters
controlIWindowControlThe control to look up.
Returns
- LayoutNode
The LayoutNode for the control, or null if not found.
GetNamedControls()
Gets all named controls as a dictionary for batch access.
public IReadOnlyDictionary<string, IWindowControl> GetNamedControls()
Returns
- IReadOnlyDictionary<string, IWindowControl>
A dictionary mapping control names to controls.
GetVisibleHeightForControl(IWindowControl)
Gets the actual visible height for a control within the window viewport. Accounts for window scrolling and clipping.
public int? GetVisibleHeightForControl(IWindowControl control)
Parameters
controlIWindowControl
Returns
- int?
GoToBottom()
Scrolls the window content to the bottom.
public void GoToBottom()
GoToTop()
Scrolls the window content to the top.
public void GoToTop()
Invalidate(bool, IWindowControl?)
Marks the window as needing redraw and optionally invalidates all controls.
public void Invalidate(bool redrawAll, IWindowControl? callerControl = null)
Parameters
redrawAllboolTrue to invalidate all controls; false for partial invalidation.
callerControlIWindowControlThe control that initiated the invalidation, to prevent recursion.
Maximize(bool)
Maximizes the window to fill the entire desktop area.
public void Maximize(bool force = false)
Parameters
forceboolIf true, bypasses the IsMaximizable check and forces maximization. Default is false, which respects the IsMaximizable property. Use force=true for programmatic maximization that should override user preferences.
Remarks
When force is false (default), the method will silently return if IsMaximizable is false. This maintains backward compatibility with existing code.
Minimize(bool)
Minimizes the window.
public void Minimize(bool force = false)
Parameters
forceboolIf true, bypasses the IsMinimizable check and forces minimization. Default is false, which respects the IsMinimizable property. Use force=true for programmatic minimization (e.g., UAC-style dialogs) that should override user preferences.
Remarks
When force is false (default), the method will silently return if IsMinimizable is false. This maintains backward compatibility with existing code.
NotifyControlFocusLost(IInteractiveControl)
Notifies the window that a control has lost focus.
public void NotifyControlFocusLost(IInteractiveControl control)
Parameters
controlIInteractiveControlThe control that lost focus.
NotifyControlGainedFocus(IInteractiveControl)
Called by controls when they gain focus (via SetFocus). Updates Window's focus tracking to keep _lastFocusedControl in sync.
public void NotifyControlGainedFocus(IInteractiveControl control)
Parameters
controlIInteractiveControlThe control that gained focus.
NotifyControlLostFocus(IInteractiveControl)
Called by controls when they lose focus (via SetFocus). Updates Window's focus tracking to keep _lastFocusedControl in sync.
public void NotifyControlLostFocus(IInteractiveControl control)
Parameters
controlIInteractiveControlThe control that lost focus.
OnKeyPressed(ConsoleKeyInfo, bool)
Raises the KeyPressed event.
protected virtual bool OnKeyPressed(ConsoleKeyInfo key, bool alreadyHandled)
Parameters
keyConsoleKeyInfoThe key information.
alreadyHandledboolIndicates whether the key was already handled.
Returns
- bool
True if the event was handled; otherwise false.
OnStateChanged(WindowState)
Raises the StateChanged event.
protected virtual void OnStateChanged(WindowState newState)
Parameters
newStateWindowStateThe new window state.
RemoveContent(IWindowControl)
Removes a control from this window and disposes it.
public void RemoveContent(IWindowControl content)
Parameters
contentIWindowControlThe control to remove.
RemovePortal(IWindowControl, LayoutNode)
Removes a portal overlay created by CreatePortal().
public void RemovePortal(IWindowControl ownerControl, LayoutNode portalNode)
Parameters
ownerControlIWindowControlThe control that owns the portal.
portalNodeLayoutNodeThe portal LayoutNode returned by CreatePortal().
RenderAndGetVisibleContent(List<Rectangle>?)
Renders the window content and returns the visible lines.
public List<string> RenderAndGetVisibleContent(List<Rectangle>? visibleRegions = null)
Parameters
visibleRegionsList<Rectangle>Optional list of screen-space rectangles representing visible portions of the window. If provided, only these regions will be painted (optimization to avoid painting occluded areas).
Returns
Restore()
Restores the window to its normal state.
public void Restore()
ScrollToControl(IWindowControl)
Scrolls the window to ensure the specified control is visible in the viewport. If the control is already fully visible, no scrolling occurs. Handles both partially visible and completely off-screen controls.
public void ScrollToControl(IWindowControl control)
Parameters
controlIWindowControlThe control to scroll into view
SetIsActive(bool)
Sets the active state of the window.
public void SetIsActive(bool value)
Parameters
valueboolTrue to activate the window; false to deactivate.
SetPosition(Point)
Sets the position of the window.
public void SetPosition(Point point)
Parameters
pointPointThe new position with X as left and Y as top.
SetSize(int, int)
Sets the window size with proper invalidation and constraint handling.
public void SetSize(int width, int height)
Parameters
SwitchFocus(bool)
Switches focus to the next or previous interactive control in the window.
public void SwitchFocus(bool backward = false)
Parameters
backwardboolTrue to move focus backward; false to move forward.
TryClose(bool)
Checks if the window can be closed by firing the OnClosing event. Does not modify any state - only queries whether close is allowed.
public bool TryClose(bool force = false)
Parameters
forceboolIf true, bypasses IsClosable check and ignores Allow from OnClosing. The OnClosing event is still fired so handlers can perform pre-close work.
Returns
- bool
True if the window can be closed; false if close was cancelled (only when force=false).
UnfocusCurrentControl()
Removes focus from the currently focused control.
public void UnfocusCurrentControl()
UpdateContentOrder(IWindowControl, int)
Changes the order of a control in the rendering sequence.
public void UpdateContentOrder(IWindowControl content, int newIndex)
Parameters
contentIWindowControlThe control to reorder.
newIndexintThe new index position for the control.
WindowIsAdded()
Called when the window has been added to the window system.
public void WindowIsAdded()
Events
Activated
Occurs when the window becomes the active window.
public event EventHandler? Activated
Event Type
Deactivated
Occurs when the window loses active status.
public event EventHandler? Deactivated
Event Type
KeyPressed
Occurs when a key is pressed while the window has focus.
public event EventHandler<KeyPressedEventArgs>? KeyPressed
Event Type
OnClosed
Occurs after the window has been closed.
public event EventHandler? OnClosed
Event Type
OnClosing
Occurs when the window is about to close, allowing cancellation.
public event EventHandler<ClosingEventArgs>? OnClosing
Event Type
OnResize
Occurs when the window is resized.
public event EventHandler? OnResize
Event Type
OnShown
Occurs when the window is first shown.
public event EventHandler? OnShown
Event Type
StateChanged
Occurs when the window state changes (Normal, Minimized, Maximized).
public event EventHandler<Window.WindowStateChangedEventArgs>? StateChanged
Event Type
UnhandledMouseClick
Occurs when a mouse click happens on empty space (no control at that position). Used by specialized windows (e.g., OverlayWindow) to detect clicks outside content.
public event EventHandler<MouseEventArgs>? UnhandledMouseClick