Hi.Ltd.Windows 2026.6.12.959

dotnet add package Hi.Ltd.Windows --version 2026.6.12.959
                    
NuGet\Install-Package Hi.Ltd.Windows -Version 2026.6.12.959
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Hi.Ltd.Windows" Version="2026.6.12.959" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Hi.Ltd.Windows" Version="2026.6.12.959" />
                    
Directory.Packages.props
<PackageReference Include="Hi.Ltd.Windows" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add Hi.Ltd.Windows --version 2026.6.12.959
                    
#r "nuget: Hi.Ltd.Windows, 2026.6.12.959"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package Hi.Ltd.Windows@2026.6.12.959
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=Hi.Ltd.Windows&version=2026.6.12.959
                    
Install as a Cake Addin
#tool nuget:?package=Hi.Ltd.Windows&version=2026.6.12.959
                    
Install as a Cake Tool

Hi.Ltd.Windows

库简介

  • Hi.Ltd.Windows 是一套面向工业场景的 Windows Forms 控件与设计时扩展库,聚焦外观定制、主题管理、Modbus 设备通讯及快速构建可视化界面。
  • 主要模块:Components 提供多态外观描述、Designs/UITypeEditors 支持设计器交互、ThemesUIManagers 实现全局主题、Devices/IO 封装硬件通讯,Data/Drawing 则沉淀通用数据结构与几何算法。
  • 所有组件均遵循可设计、可序列化、可克隆的模式,方便通过设计器或代码批量生成统一的界面风格。

组件使用样例

HButton - 按钮控件

基本用法
// 创建按钮并绑定地址
var button = new HButton
{
    Text = "启动",
    Location = new Point(10, 10),
    Size = new Size(100, 40),
    Address = new Address 
    { 
        SoftType = SoftType.M, 
        Index = 100, 
        DataType = DataType.Bit 
    },
    ActionType = ActionType.Switch // 切换动作
};

// 配置多状态外观
button.Appearances.Add(new ButtonAppearance
{
    State = 0,
    Text = "停止",
    BackColor = Color.Gray,
    ForeColor = Color.White
});

button.Appearances.Add(new ButtonAppearance
{
    State = 1,
    Text = "运行",
    BackColor = Color.Green,
    ForeColor = Color.White
});
设值动作
var btnSet = new HButton
{
    Text = "设置值",
    Address = new Address { SoftType = SoftType.D, Index = 200 },
    ActionType = ActionType.Set,
    SetValue = 100 // 点击后写入值 100
};
自增/自减
var btnInc = new HButton
{
    Text = "+",
    Address = new Address { SoftType = SoftType.D, Index = 300 },
    ActionType = ActionType.Increment,
    MaximumValue = 1000 // 最大值限制
};

var btnDec = new HButton
{
    Text = "-",
    Address = new Address { SoftType = SoftType.D, Index = 300 },
    ActionType = ActionType.Decrement,
    MinimumValue = 0 // 最小值限制
};
权限控制
var btnAdmin = new HButton
{
    Text = "管理员操作",
    Rights = 2, // 需要权限等级 2
    Address = new Address { SoftType = SoftType.M, Index = 500 }
};

HLabel - 标签控件

显示 PLC 数值
var label = new HLabel
{
    Text = "温度",
    Location = new Point(10, 10),
    Size = new Size(200, 30),
    Address = new Address 
    { 
        SoftType = SoftType.D, 
        Index = 100,
        DataType = DataType.UInt16,
        DecimalPlaces = 1 // 显示 1 位小数
    },
    TextAlign = ContentAlignment.MiddleLeft
};
// 自动显示格式化的数值,如 "25.5"
多状态显示
var statusLabel = new HLabel
{
    Text = "状态",
    Appearances = new LabelAppearanceCollection
    {
        new LabelAppearance
        {
            State = 0,
            Text = "待机",
            BackColor = Color.Gray,
            ForeColor = Color.White
        },
        new LabelAppearance
        {
            State = 1,
            Text = "运行",
            BackColor = Color.Green,
            ForeColor = Color.White
        },
        new LabelAppearance
        {
            State = 2,
            Text = "报警",
            BackColor = Color.Red,
            ForeColor = Color.White
        }
    },
    Address = new Address { SoftType = SoftType.M, Index = 200 }
};
// 根据地址值自动切换状态和外观

HTextBox - 文本框控件

基本输入
var textBox = new HTextBox
{
    Location = new Point(10, 10),
    Size = new Size(200, 30),
    Address = new Address 
    { 
        SoftType = SoftType.D, 
        Index = 300,
        DataType = DataType.UInt16,
        DecimalPlaces = 2
    },
    Watermark = new Watermark<HTextBox>
    {
        Content = "请输入数值",
        ForeColor = Color.Gray,
        Font = new Font("微软雅黑", 9)
    },
    MinimumValue = 0,
    MaximumValue = 1000
};
// 点击后弹出输入对话框,输入值写入 PLC
带边框样式
var styledTextBox = new HTextBox
{
    BorderEnabled = true,
    BorderColor = Color.Blue,
    BorderWidth = 2,
    BorderPadding = new Padding(5),
    SyncPaddingWithBorder = true
};
权限控制
var protectedTextBox = new HTextBox
{
    Address = new Address { SoftType = SoftType.D, Index = 400 },
    Rights = 1, // 需要权限等级 1 才能输入
    Tag = "重要参数"
};

HPanel - 面板控件

容器面板
var panel = new HPanel
{
    Dock = DockStyle.Fill,
    Radius = 10,
    FilletStyle = FilletStyle.All,
    Gradient = new Gradient<HPanel>
    {
        Enabled = true,
        StartColor = Color.FromArgb(240, 240, 240),
        EndColor = Color.FromArgb(255, 255, 255),
        Angle = 90 // 垂直渐变
    },
    Appearances = new PanelAppearanceCollection
    {
        new PanelAppearance
        {
            State = 0,
            BackColor = Color.White,
            Text = "正常状态"
        },
        new PanelAppearance
        {
            State = 1,
            BackColor = Color.Yellow,
            Text = "警告状态"
        }
    }
};
用于界面重定向
var containerPanel = new HPanel
{
    Name = "MainPanel",
    Dock = DockStyle.Fill,
    RedirctionIndex = 0 // 重定向索引
};
Factory.AddOrUpdatePanel(containerPanel);

HPictureBox - 图片框控件

状态图片切换
var pictureBox = new HPictureBox
{
    Location = new Point(10, 10),
    Size = new Size(100, 100),
    Address = new Address { SoftType = SoftType.M, Index = 500 },
    Appearances = new PictureBoxAppearanceCollection
    {
        new PictureBoxAppearance
        {
            State = 0,
            Image = Properties.Resources.OffIcon,
            BackColor = Color.Gray
        },
        new PictureBoxAppearance
        {
            State = 1,
            Image = Properties.Resources.OnIcon,
            BackColor = Color.Green
        }
    }
};
// 根据地址值自动切换图片

HLamp - 指示灯控件

圆形指示灯
var lamp = new HLamp
{
    Location = new Point(10, 10),
    Size = new Size(50, 50),
    Address = new Address { SoftType = SoftType.M, Index = 600 },
    Appearances = new AppearanceSettingCollection
    {
        new AppearanceSetting
        {
            State = 0,
            BackColor = Color.Gray,
            CenterBackColor = Color.DarkGray // 中心颜色,形成渐变效果
        },
        new AppearanceSetting
        {
            State = 1,
            BackColor = Color.Green,
            CenterBackColor = Color.Lime
        }
    }
};
// 使用 PathGradientBrush 绘制发光效果

HSwitch - 开关按钮

双态开关
var switchBtn = new HSwitch
{
    Text = "开关",
    Location = new Point(10, 10),
    Size = new Size(100, 40),
    Address = new Address { SoftType = SoftType.M, Index = 700 },
    OnBackColor = Color.Green,
    OnForeColor = Color.White,
    OnText = "ON",
    OffBackColor = Color.Gray,
    OffForeColor = Color.White,
    OffText = "OFF",
    Radius = 5,
    FilletStyle = FilletStyle.All
};

HProgressBar - 进度条

基本进度条
var progressBar = new HProgressBar
{
    Location = new Point(10, 10),
    Size = new Size(300, 30),
    Minimum = 0,
    Maximum = 100,
    Value = 50,
    ChannelColor = Color.LightGray,
    SliderColor = Color.Blue,
    TipsBefore = "进度: ",
    TipsAfter = "%",
    TipsPosition = TipsPosition.Follow // 提示文本跟随滑块
};
绑定 PLC 地址
var plcProgressBar = new HProgressBar
{
    Address = new Address { SoftType = SoftType.D, Index = 800 },
    Maximum = 1000,
    ChannelHeight = 20,
    SliderHeight = 25 // 滑块高于通道
};
// 根据 PLC 地址值自动更新进度

HCircularProcess - 环形进度

环形进度显示
var circularProcess = new HCircularProcess
{
    Location = new Point(10, 10),
    Size = new Size(200, 200),
    Value = 75,
    MaxValue = 100,
    InnerRadius = 60,
    CircularBackColor = Color.LightGray,
    ProcessColor = Color.Blue,
    InnerCircularBackColor = Color.White,
    Format = "{0}%" // 显示百分比
};

HIcon - 图标控件

字体图标
var icon = new HIcon
{
    Location = new Point(10, 10),
    Size = new Size(50, 50),
    Icon = new IconInfo { Index = 100, Name = "Play" },
    IconSize = 32,
    IconColor = Color.Blue,
    Address = new Address { SoftType = SoftType.M, Index = 900 }
};

// 根据状态切换颜色
icon.OnIconColor = Color.Green;
icon.OffIconColor = Color.Gray;

HRedirectionButton - 重定向按钮

界面导航
var navButton = new HRedirectionButton
{
    Text = "设置页面",
    Location = new Point(10, 10),
    Size = new Size(100, 40),
    Redirection = new Redirection
    {
        LoaderName = "MainPanel", // Panel 名称
        RedirectionName = "SettingsPage", // 用户控件类型名
        Index = 0
    },
    Appearances = new RedirectionButtonAppearanceCollection
    {
        new RedirectionButtonAppearance
        {
            State = 0,
            BackColor = Color.Gray,
            Text = "设置"
        },
        new RedirectionButtonAppearance
        {
            State = 1,
            BackColor = Color.Blue,
            Text = "设置 (当前)"
        }
    }
};

HComparisionButton - 比较按钮

数值比较
var compareBtn = new HComparisionButton
{
    Text = "温度比较",
    Location = new Point(10, 10),
    Size = new Size(200, 40),
    MonitorAddress = new Address { SoftType = SoftType.D, Index = 1000 },
    MonitorAddress2 = new Address { SoftType = SoftType.D, Index = 1001 },
    Appearances = new ComparisionButtonAppearanceCollection
    {
        new ComparisionButtonAppearance
        {
            State = 0, // 相等
            Text = "温度正常",
            BackColor = Color.Green,
            MonitorForeColor = Color.White
        },
        new ComparisionButtonAppearance
        {
            State = 1, // 大于
            Text = "温度偏高",
            BackColor = Color.Orange,
            MonitorForeColor = Color.Red
        },
        new ComparisionButtonAppearance
        {
            State = -1, // 小于
            Text = "温度偏低",
            BackColor = Color.Blue,
            MonitorForeColor = Color.Cyan
        }
    }
};
// 自动比较两个地址的值并显示结果

HRollTextBox - 滚动文本

报警滚动显示
var rollText = new HRollTextBox
{
    Dock = DockStyle.Top,
    Height = 30,
    BackColor = Color.Red,
    ForeColor = Color.White,
    RollStyle = RollStyle.Left,
    Speed = 2,
    Interval = 50,
    Separator = " | "
};

// 动态更新内容
rollText.Source = "报警1 | 报警2 | 报警3";

HRichTextBox - 日志控件

日志输出
var logBox = new HRichTextBox
{
    Dock = DockStyle.Fill,
    MaxLines = 1000,
    ReadOnly = true
};

// 订阅消息事件
EventHelper.OnMessageChanged += (message, color) =>
{
    logBox.AppendText($"[{DateTime.Now:HH:mm:ss}] {message}\r\n", color);
};
图片轮播
var carousel = new Carousel
{
    Dock = DockStyle.Fill,
    ImageList = imageList, // 图片列表
    AutoPlay = true,
    Interval = 2000, // 2 秒切换
    Direction = ScrollDirection.Horizontal,
    IndicatorStyle = IndicatorStyle.Dots,
    IndicatorColor = Color.White,
    IndicatorActiveColor = Color.Blue,
    Radius = 10
};

// 订阅选中事件
carousel.SelectIndexChanged += (s, e) =>
{
    var index = e.Index;
    var appearance = e.Appearance;
    // 处理选中项
};

HForm - 主窗体

带数据刷新的窗体
public partial class MainForm : HForm
{
    public MainForm()
    {
        InitializeComponent();
        
        // 自动订阅 OnValueChanged 事件
        // 自动刷新所有子控件中的 IPlcEntity
    }
}

HUserControl - 用户控件

可缩放用户控件
public partial class MyUserControl : HUserControl
{
    public MyUserControl()
    {
        InitializeComponent();
        
        AutoScaleEnabled = true; // 启用自动缩放
        FixedSize = Size; // 记录初始尺寸
        FontSize = Font.Size; // 记录初始字体大小
        
        // 运行时自动按比例缩放
    }
}

快速查找

按任务查找

按控件类型查找

  • 按钮类HButtonHSwitchHRedirectionButtonHComparisionButton
  • 显示类HLabelHTipsHPictureBoxHIconHLamp
  • 输入类HTextBoxHComboBoxHEditCheckBox
  • 容器类HPanelHUserControlHFormHGroupBoxHTabControl
  • 特殊类HProgressBarHCircularProcessHLineHRollTextBoxCarousel

按功能查找

文档目录

项目结构概览

Hi.Ltd.Windows/
├── Components/          # 外观组件(AppearanceSetting、ButtonAppearance 等)
├── Collections/         # 集合类(AppearanceSettingCollection)
├── CollectionEditors/  # 集合编辑器(设计时支持)
├── Forms/               # 自定义控件(HButton、HLabel、HTextBox 等)
│   └── Composition/    # 组合控件(Input、HMessageBox、AddressEditorForm 等)
├── Designs/             # 设计时支持(Designer、Gradient、Watermark 等)
├── Themes/              # 主题系统(Theme 基类及 18+ 种具体主题)
├── UIManagers/          # UI 管理器(ThemeManager)
├── Data/                # 数据模型(Address、ValueRange、Redirection 等)
├── Drawing/             # 几何工具(PointD、Circle、Line 等)
├── Interfaces/          # 接口定义(IPlc、IPlcEntity、ITheme 等)
├── IO/                  # 通讯适配器(SerialPortAdapter、SocketAdapter)
├── Devices/              # 设备类(ModbusDevice)
├── Converters/           # 类型转换器(AddressConverter 等)
├── UITypeEditors/        # UI 类型编辑器(AddressEditor、IconPickerEditor 等)
├── Provider/             # 类型描述提供程序(属性过滤)
├── Events/               # 事件参数类(ThemeChangedEventArgs 等)
├── Delegates/            # 委托定义(Invokes.cs)
├── Fonts/                # 字体图标系统(IconManager、IconInfo 等)
├── Dialogs/              # 对话框(AddressDialog)
├── Utilities/            # 工具类(NativeMethod、扩展方法等)
├── EqualityComparer/      # 相等性比较器(AddressEqualityComparer)
├── Sites/                # 站点类(FakeSite)
├── Factory.cs            # 窗体工厂(实例管理、地址收集、重定向)
├── Initialize.cs         # 初始化辅助(批量扫描与地址收集)
├── Application.cs         # 应用程序管理(App 类)
└── _using.cs             # 全局 using 指令

核心特性

  • 30+ 工业控件:按钮、标签、文本框、面板、图片框等,均支持 PLC 地址绑定
  • 多状态外观:每个控件支持多状态外观配置,状态驱动 UI 切换
  • 18+ 主题系统:内置多种主题,支持一键切换全局样式
  • 设计时支持:完整的 Visual Studio 设计器支持,可视化编辑外观
  • PLC 通讯:统一的 IPlc 接口,支持 Modbus、串口、网络等多种通讯方式
  • 地址管理:自动收集、缓存、去重地址,支持动态范围与偏移
  • 界面重定向:支持窗体与用户控件的动态加载与切换
  • 字体图标:内置图标字体系统,支持矢量图标渲染
  • 事件总线:全局事件分发机制,解耦组件通信
  • 性能优化:LRU 缓存、批量更新、资源自动管理

组件功能说明(按文件)

Components/AppearanceSetting.cs

用于描述任意控件可重用的状态外观(颜色、文本、图像等),也是集合编辑器与主题管理的通用数据单元。

参数/属性 作用
State 数值状态标识,用于在不同场景下切换显示。
Text 该状态需要呈现的文本内容。
BackColor / CenterBackColor 渐变或多段背景的颜色定义。
ForeColor 与文本匹配的前景色。
BackgroundImage 补充性的背景图像。
Tag 绑定自定义数据,利于运行期逻辑。
Appearance (HControlAppearance) 统一的边框与鼠标状态外观。

Components/ButtonAppearance.cs

定义 HButton 多状态外观(颜色、文本、图像、边框),并在属性变化时驱动控件重绘。

参数/属性 作用
Name 设计期名称,默认通过 NativeMethod 生成。
BackColor / ForeColor 指定当前状态的主色与文字色。
Image / BackgroundImage 前景图与背景图,赋值即自动克隆以避免资源共享。
Text 按钮在该状态下的显示文本。
State 整型状态值,用于区分不同外观。
Tag 绑定业务数据。
Appearance 复用 HControlAppearance 配置边框/指示效果。
HButton 只读引用,指向拥有该外观的控件,便于回调 Invalidate()

Components/CarouselAppearance.cs

面向 Carousel 轮播控件的外观配置,额外结合 StateClickEditor 支持设计器双击即生成状态事件。

参数/属性 作用
BackColor / ForeColor 当前项背景与文本颜色。
Image / BackgroundImage 轮播项的主图与底图。
Text 轮播项标题或描述。
State 状态值,使用 StateClickEditor 时可自动生成 Click 事件处理。
Tag 用户数据(如绑定的资源 ID)。
Appearance 共享的边框与指示灯样式。
Carousel 所属轮播控件引用,用于刷新与事件派发。

Components/ComparisionButtonAppearance.cs

HComparisionButton 提供主/监视前景色等差异化属性,适合多状态比较场景。

参数/属性 作用
BackColor / ForeColor 常规底色与文字色。
MonitorForeColor 监控显示区的独立前景色,便于对比状态。
Image / BackgroundImage 差异图像资源。
Text 比较按钮的状态文本。
State 状态编号。
Tag 自定义数据。
Appearance 边框与鼠标状态样式。
HComparisionButton 关联控件引用,便于在销毁时从集合移除。

Components/LabelAppearance.cs

封装 HLabel 的颜色、文本与图像配置,强调轻量级状态切换。

参数/属性 作用
BackColor / ForeColor 标签背景与字体颜色。
Image 状态对应的小图标,自动克隆与释放。
Text 标签文本。
State 状态值。
Tag 绑定业务对象。
Appearance 边框/高亮风格。
HLabel 关联控件引用。

Components/PanelAppearance.cs

控制 HPanel 在不同状态下的背景、图像与文本,常用于动态看板或卡片布局。

参数/属性 作用
BackColor / ForeColor 面板背景与文字色。
Image / BackgroundImage 内容图与背景图,赋值时自动 Clone/Dispose。
Text 状态文字描述。
State 状态标识。
Tag 用户数据。
Appearance 边框与交互反馈。
HPanel 关联控件。

Components/PictureBoxAppearance.cs

用于 HPictureBox,聚焦图像资源管理(含默认检测、Clone/Dispose)及背景色切换。

参数/属性 作用
BackColor 图片容器背景色。
Image 主显示图,内部 Clone,释放时自动 Dispose。
BackgroundImage 背景叠加图。
State 状态值,可用于动画或报警切换。
Tag 绑定业务数据。
Appearance 边框、鼠标反馈定义。
HPictureBox 所属图片控件。

Components/RedirectionButtonAppearance.cs

服务于 HRedirectionButton,除常规外观外,还描述重定向目标的状态展示。

参数/属性 作用
BackColor / ForeColor 重定向按钮颜色。
Image / BackgroundImage 状态图像。
Text 状态描述文本。
State 用于区分不同跳转配置。
Tag 自定义元数据(如目标窗体标识)。
Appearance 边框/高亮样式。
HRedirectionButton 关联控件。

Components/UserControlAppearance.cs

HUserControl 提供状态式背景配置,简化复合控件在主题切换时的处理。

参数/属性 作用
BackColor / ForeColor 控件背景与文字色。
BackgroundImage 状态背景图。
State 状态编号。
Tag 业务数据。
Appearance 通用边框样式。
HUserControl 关联控件引用,用于设计期同步。

Components/StateClickEditor.cs

自定义 UITypeEditor,在设计器中双击 CarouselAppearance.State 即可:

  • 自动生成唯一的 Click 事件处理方法并写入 InitializeComponent
  • 调用 EventBindingService.ShowCode 打开对应代码位置。
  • 触发 CarouselAppearance.PerformClick() 以预览行为。
参数/方法 作用
GetEditStyle 返回 Modal,让属性面板以对话框形式触发编辑。
EditValue 解析选中实例、生成事件、调用 PerformClick,最终返回原值。

集合与集合编辑器

Collections/AppearanceSettingCollection.cs

序列化友好的 AppearanceSetting 集合,实现状态快速索引与克隆。

成员 作用
_stateMap 使用 Dictionary<int, AppearanceSetting> 缓存状态到配置的映射,加速查找。
Clone() 深拷贝集合中的所有 AppearanceSetting,避免引用共享。
GetAppearanceSetting(state) 通过状态值快速返回对应外观配置。
GetDefaultTemplate() 生成“默认/变更后”两套示例数据,便于设计器预填。
GetObjectData / OnDeserialized 支持序列化/反序列化并重建 _stateMap

CollectionEditors/AppearanceSettingCollectionEditor.cs

面向 AppearanceSettingCollection 的设计时集合编辑器。

方法/重写点 作用
SetItems 覆盖默认集合写入逻辑,先清空再逐项添加,避免 Designer 生成重复代码。
CollectionEditor(Type) 构造函数映射到需要编辑的集合类型。

CollectionEditors/ButtonAppearanceCollectionEditor.cs

专为 HButton.ButtonAppearanceCollection 服务的编辑器,强化设计期体验。

方法/重写点 作用
SetItems 仅在提供 ButtonAppearance[] 时刷新集合,并捕获 ExceptionCollection
CreateInstance 借助 IDesignerHost 创建组件并自动绑定 Owner
DestroyInstance 优雅释放设计期组件,避免遗留。
GetDisplayText 在集合对话框展示设计器生成名称。

CollectionEditors/CarouselAppearanceCollectionEditor.cs

Carousel.CarouselAppearanceCollection 配套,支持轮播项设计。

方法/重写点 作用
SetItems 无论是否有新值都先 Clear(),确保删除操作被序列化。
CreateInstance 通过设计器宿主创建 CarouselAppearance 并设置 Owner
DestroyInstance 调用宿主销毁,保持设计期资源整洁。
GetDisplayText 根据 Site.Name 展示项名。

CollectionEditors/ComparisionButtonAppearanceCollectionEditor.cs

服务于 HComparisionButton 的状态编辑器。

方法/重写点 作用
SetItems 清空集合后批量加入 ComparisionButtonAppearance
CreateInstance 调用设计器宿主创建项并绑定 Owner
DestroyInstance 通过宿主销毁,避免泄露。
GetDisplayText 自定义集合弹窗中的条目标题。

CollectionEditors/LabelAppearanceCollectionEditor.cs

HLabel.LabelAppearanceCollection 提供快速维护界面。

方法/重写点 作用
SetItems 统一清空并重建集合,确保 Designer 只写一次。
CreateInstance 利用宿主创建 LabelAppearance 并设置 Owner
DestroyInstance 调用宿主销毁组件。
GetDisplayText 显示标签外观的设计期名称。

CollectionEditors/PanelAppearanceCollectionEditor.cs

面向 HPanel 的外观集合编辑。

方法/重写点 作用
SetItems 捕获 ExceptionCollection,在 Designer 中安全更新。
CreateInstance 创建后绑定 HPanel 以便及时刷新。
DestroyInstance 借助宿主释放对象。
GetDisplayText 展示面板外观名称。

CollectionEditors/PictureBoxAppearanceCollectionEditor.cs

HPictureBox.PictureBoxAppearanceCollection 对应,强调资源管理。

方法/重写点 作用
SetItems 逐项添加 PictureBoxAppearance,保持集合状态。
CreateInstance 调用基类创建后补充 Owner 引用。
DestroyInstance 主动调用 Dispose() 释放图像资源。
GetDisplayText 默认显示名称或 Site 名。

Designs/RedirectionButtonAppearanceCollectionEditor.cs

命名位于 Designs 下,但本质上也是集合编辑器,用于 HRedirectionButton

方法/重写点 作用
CreateInstance 使用 IDesignerHost 创建项并关联 Owner,保证序列化正常。
DestroyInstance 优先通过宿主销毁,保持设计期文档干净。
GetDisplayText 为集合对话框提供可读的重定向项名称。

窗体控件

Forms/HTextBox.cs

工业人机界面专用文本框,集成 PLC 通讯、动态阈值、水印与自绘边框,适合直接绑定软元件地址进行读写。

参数/属性 作用
Address 主通讯地址(含软元件类型、数据类型、小数位)并支持 IsAddressAvailable 快速判断可用性。
AssociatedAddress 联动地址,可用于互锁或级联显示。
MinimumAddress / MaximumAddress + MinimumValue / MaximumValue 指定动态或固定上下限,当 PLC 返回范围值时自动更新。
Rights + CheckAuthority() 权限等级控制,点击前校验当前用户权限,失败弹窗提示。
ILock.CheckLock() 结合全局锁屏状态阻止写入操作。
OffsetEnabled + AddressOffsetChanged() 订阅 EventHelper.OnAddressOffsetChanged,统一偏移所有绑定地址。
Watermark 通过 Watermark<T> 对象配置提示文字、字体与颜色,在文本为空时绘制。
BorderColor / BorderWidth / BorderPadding / BorderEnabled / SyncPaddingWithBorder 使用 BorderDecorator 自绘边框,支持同步 Padding。
TagVisible 控制是否在文本前展示 Tag 描述,可与实时值组合显示。
MonitorEnabled / MonitorAddress 预留监视接口,当前默认禁用。
Instance(IPlc) / Update() 通过 EventHelper.OnCommunication 注入 PLC 句柄,并在数据包到达后更新文本内容、小数格式与范围。
Input() 点击后弹出 Input 对话框,自动计算屏幕位置并根据 ValueRange 限制输入,确认后调用 _plc.WriteDevice
WndProc WM_PAINT 中绘制水印与边框,确保设计期/运行期一致的外观体验。

Forms/HButton.cs

多态 PLC 按钮控件,支持开关/设值/自增自减/延时等行为,结合 ButtonAppearance 集合实现状态驱动的外观切换。

参数/属性 作用
Address 写入地址,可配置 SetValue、取反 NegationEnabled 以及动态最小/最大值地址。
MonitorAddress 单独的监视地址用于读取状态,与写入地址分离;配套 IsMonitorAddressAvailableMonitorHashCode
MaximumAddress / MinimumAddress + MaximumValue / MinimumValue 支持 PLC 动态范围或本地阈值,配合 IsRangeAddressAvailable 校验。
ActionType 控件动作枚举:Switch(循环切换)/Set(写固定值)/Increment/Decrement/DelaySet/Reset 等,对应 OnClickOnMouseDown/Up 的写入逻辑。
Rights / CheckAuthority() & CheckLock() IAuthorityFilterILock 联动,阻止未授权或锁屏状态下的交互。
Radius / FilletStyle / Gradient UI 定制:圆角、渐变、局部圆角控制,UpdateRegion() 在尺寸变化时更新 Region。
Appearances (ButtonAppearanceCollection) 设计器可编辑的状态集合,UpdateDisplay() 根据 CurrentState 应用文本、颜色、图片及 FlatAppearance 边框。
TouchEnabled + WndProc WM_POINTER 消息转换为鼠标事件,屏蔽长按右键,提升触摸屏体验。
Instance(IPlc) / Update() 订阅 EventHelper.OnCommunication,接收 PLC 数据更新 _currentState 并刷新 UI。
Dispose() 深度清理 ButtonAppearance 集合与图像资源,避免设计期/运行期泄漏。

Forms/HPanel.cs

可分组容器控件,提供圆角、渐变填充、多状态外观与同步上下文封装,适合作为主题化布局容器或动态画布。

参数/属性 作用
Radius / FilletStyle 配置圆角半径与四角显示方式,UpdateRegion() 保持 Region 与尺寸同步。
Gradient 通过 Gradient<HPanel> 定义背景渐变,支持 Blend 与背景图叠加;OnPaint 里开启抗锯齿绘制。
Appearances (PanelAppearanceCollection) 设计器中配置多状态外观(文本/背景/前景/背景图),CurrentState 变化时 UpdateDisplay() 自动套用。
Rights / RedirctionIndex 面向权限控制和场景索引用;重定向索引用于跨控件跳转。
IsContainer 固定为 true,强调面板可承载子控件。
Post() / Send() 封装 SynchronizationContext 的异步/同步调度,当上下文不存在时回落到 BeginInvoke
WndProc 忽略 WM_ERASEBKGND 以减少闪烁,配合 DoubleBuffered 实现平滑重绘。

Forms/HLabel.cs

PLC 标签控件,支持圆角、渐变、LabelAppearance 多状态切换,可将实时值或自定义文本与状态绑定。

参数/属性 作用
Address 默认连接到 SoftType.DUpdate() 时根据小数位格式化并写入文本。
DynamicThresholdEnabled / MaximumAddress / MinimumAddress 预留动态上下限接口,适合扩展报警或者区间展示。
Gradient / Radius / FilletStyle 自绘渐变和圆角;尺寸变化时 UpdateRegion() 调整 Region。
Appearances (LabelAppearanceCollection) 根据 State 替换 Text/BackColor/ForeColor/Image,通过设计器编辑。
Rights 保留权限字段,便于与整体权限系统打通。

Forms/HPictureBox.cs

状态化图片框,内建圆角、渐变及 PictureBoxAppearance 集合,常用于指示灯、动画或多帧展示。

参数/属性 作用
Address 绑定 PLC 位/字地址,Update() 时根据返回值切换状态。
Gradient / Radius / FilletStyle 与按钮/面板一致的可视化能力,支持渐变叠加背景图。
Appearances (PictureBoxAppearanceCollection) 为每个状态配置前景/背景图与颜色,UpdateDisplay() 自动套用。
Post() / Send() HPanel 相同的同步上下文封装,便于跨线程刷新图片。

Forms/HComparisionButton.cs

用于对两个地址值进行比较并根据结果切换外观/文本的复合按钮,常见于上下限报警、参数对比场景。

参数/属性 作用
Address + MonitorAddress / MonitorAddress2 同时读取多个地址,支持双数据源比较;IsMonitorAddressAvailable 需两路监视地址均启用。
Content / 重写的 Text 允许独立配置静态文本、比较描述。
MaximumValue / MinimumValue 限定自增/自减模式范围,用于增量操作。
Appearances (ComparisionButtonAppearanceCollection) 针对比较结果状态应用色彩、图像、MonitorForeColor 等。
ActionType & Rights/Lock 延续 HButton 的动作、权限、锁屏机制,可在 OnClick 中写入结果。

Forms/HRedirectionButton.cs

界面导航控件,可根据 Redirection 配置切换窗体或页面,并以 RedirectionButtonAppearance 呈现激活状态。

参数/属性 作用
Redirection / Redirections 支持单个或多个跳转目标(载体名称、界面名、索引)。
Appearances 通过状态集合显示当前选中/未选中颜色、文本、图片等。
Gradient / Radius / FilletStyle HButton 一致的可视化能力。
Rights / CheckAuthority() 点击前执行权限校验。
LoadRedirections() 调用 Loader.Load(name, index) 完成实际页面切换,并可同步兄弟按钮状态。

Forms/HSwitch.cs

PLC 开关按钮,继承 Button 但内置 On/Off 成组外观、图像、文本与 PLC 写入逻辑,适合实现双态拨动/切换。

参数/属性 作用
Address / MonitorAddress 写入与监视地址可分离,支持 NegationEnabled 取反、SetValue 指定写入值。
On/OffBackColorOn/OffForeColorOn/OffImageOn/OffBackgroundImageOn/OffText 直接定义双态的颜色、文本、图片。
Gradient / Radius / FilletStyle 渐变、圆角控制,与 HButton 相同。
ActionType / Rights / CheckAuthority() / CheckLock() 复用按钮动作与安全机制。
UpdateDisplay() 根据 PLC 状态刷新双态外观,鼠标悬停时还会调整渐变亮度。

Forms/HLamp.cs

基于 HControl 的指示灯控件,屏蔽普通文本/背景属性,专注于圆形渐变填充,常用于表示运行、报警、禁用等状态。

参数/属性 作用
Appearances(继承自 HControl 每个状态提供 BackColor/CenterBackColorOnPaintBackColor 使用 PathGradientBrush 绘制发光效果。
Radius 自动受控,确保不超过控件的一半尺寸。
文本相关属性 被隐藏,保证控件只呈现纯指示效果。

Forms/HTips.cs

轻量级提示/状态文本控件,结构类似 HLabel,但简化为直接显示 PLC 地址值或梯形文本。

参数/属性 作用
Address 绑定软元件,Update() 将数值按小数位格式化为文本。
Gradient / Radius / FilletStyle 支持渐变背景和圆角提示框。
Rights 保留权限字段方便统一控制。

Forms/HProgressBar.cs

自绘进度条,允许选择通道/滑块高度、颜色、提示文本位置,适合显示耗时或产量进度。

参数/属性 作用
ChannelColor / SliderColor / ForeBackColor 控制通道、滑块和提示背景颜色。
ChannelHeight / SliderHeight 自定义高度,支持滑块高于通道。
TipsBefore / TipsAfter / IsShowMaxinumTips / TipsPosition 配置进度文本(前缀/后缀、最大值提示、显示位置含随滑块移动)。
StopPainting / PaintedBack 减少重绘开销,极值时暂停背景重画。

Forms/HComboBox.cs

扩展自 ComboBox,实现 IContext,可通过 Post/Send 在 UI 线程安全地更新数据源或选项,方便与 PLC 线程交互。

参数/属性 作用
Post / Send 封装 SynchronizationContext,在通讯线程中安全更新下拉列表。
IsContainer 固定为 false,强调用于数据选择场景。

Forms/HControl.cs

自定义控件的抽象基类,集中实现 PLC 地址绑定、监视地址、动态阈值、AppearanceSettingCollection、主题/权限接口,是 HLampHCircularProcess 等控件的基础。

参数/属性 作用
Address / MonitorAddress / MaximumAddress / MinimumAddress 标准化所有控件的数据绑定入口,支持取反、动态范围。
AppearanceSettingCollection Appearances 定义多状态的背景、前景、文本;派生类复用 UpdateDisplay
SetStyles / OnPaintBackground 统一启用双缓冲并模拟透明背景。
IPlcEntity / IAuthorityFilter / ILock / IContext / IFillet / ITheme 基类即实现所有接口,子控件获得一致的通讯、权限、圆角、主题能力。

Forms/HUserControl.cs

容器控件基类,支持圆角、渐变、多状态外观,并额外提供子控件批量刷新和自动缩放能力。

参数/属性 作用
AutoScaleEnabled / FixedSize / FontSize 记录初始尺寸与字体,运行时按比例缩放。
Appearances (UserControlAppearanceCollection) 与主题/状态绑定,切换时可统一刷新内部控件。
FlushInterval / Common_UCLoadValueChanged 订阅 EventHelper,按间隔遍历子控件地址并批量更新。
IsContainer 默认 true,强调用于承载其他控件。

Forms/HIcon.cs

字体图标显示控件,基于 PictureBox,隐藏常规图片属性,只通过 IconInfo 渲染矢量字体。

参数/属性 作用
Icon (IconInfo) 选择 Fonts/IconManager 中的字形,支持设计时序列化。
IconSize / IconColor / OnIconColor / OffIconColor 控制字形尺寸与颜色,可配合 PLC 状态切换。
Address 允许与 PLC 状态联动,决定显示哪个图标或颜色。

Forms/HLine.cs

轻量级分隔线控件,支持水平/垂直方向、虚线样式、渐变颜色,并可选择是否穿过文本绘制。

参数/属性 作用
Orientation 切换横向/纵向线条时自动调整控件尺寸。
LineWidth / LineColor / LineEndColor / DashStyle 控制线宽、颜色及渐变样式。
CorssTextEnabled / TextAlign 可在标题文字中断处分段绘线,或让线条穿过文字。
Padding 影响自动调整的留白区域。

Forms/HCircularProcess.cs

环形进度展示控件,以双层圆绘制背景与进度弧,适合可视化任务进度。

参数/属性 作用
CircularBackColor / InnerCircularBackColor 控制外/内圆颜色。
ProcessColor / InnerBorder 定义进度弧线与内圆边框。
InnerRadius / MaxValue / Value 设定内圆半径与数值范围,Value 达到 MaxValue 触发 ProcessDone 事件。
Format 控制中心文字显示格式(百分比等)。

Forms/HForm.cs

窗口级容器,继承 Form,自动订阅 EventHelper.OnValueChanged,用于批量刷新窗口内所有 IPlcEntity

参数/属性 作用
Common_UCLoadValueChanged 扫描子控件,读取地址缓存并调用 Update
Post / Send 窗体级同步上下文封装,便于跨线程刷新。
IsContainer 固定 true,强调承载控件集合。

Forms/HEditCheckBox.cs

可右键编辑文字的复选框,集成 IME 控制确保输入半角。

参数/属性 作用
TextBox 隐藏文本框用于编辑,右键文字区域弹出。
ForceHalfWidthMode 调用 imm32 将输入法切换为半角防止全角字符。
StartEditing() / EndEditing() 控制编辑流程(Enter 保存、Esc 取消)。

Forms/HGroupBox.cs

自绘标题的分组框,橡皮擦背景后居中绘制标题文本。

参数/属性 作用
Text 覆写自定义绘制,允许空文本或居中标题。
Post / Send 继承 IContext,可安全与 PLC 线程交互。

Forms/HTabControl.cs

支持自绘页签、圆角容器及隐藏标签页的 TabControl。

参数/属性 作用
Radius 控制整个控件的圆角 Region。
TitleBackColor / TitleForeColor / TitleSelectedBackColor / TitleSelectedForeColor 定义普通/选中标签颜色。
TabsVisible 运行期隐藏页签,仅保留内容区。
Post / Send 实现 IContext,方便跨线程切换页签。

Forms/HRollTextBox.cs

滚动文字/报警条,内置 Timer 控制文本在矩形内滚动,支持三种滚动方向。

参数/属性 作用
RollStyle / Speed / Interval 控制滚动方向、步长与刷新频率。
Source / Separator / _activeAlarms 根据 Address 值聚合报警文本并以分隔符拼接。
UpdateContent() 根据 PLC 地址集合实时增删报警。

Forms/HDataGridView.cs

定制风格的数据网格,预设字体、行高、自动列宽,并约定与 OperationTable 绑定。

参数/属性 作用
Load<T>() OperationTable 派生类的列定义应用到网格。
BindingDataSource<T>() OperationTable 集合转换为行并刷新显示。
预设属性 SelectionModeAutoSizeColumnsModeRowHeadersVisible 等均已在构造函数中配置。

Forms/HRichTextBox.cs

彩色日志/消息输出控件,监听 EventHelper.OnMessageChanged 批量渲染消息,并限制最大行数。

参数/属性 作用
MaxLines 控制保留的最大行数,超出时自动裁剪旧消息。
UpdateContent() / OnMessageChanged() 批量累积消息并延迟刷新,保持 UI 流畅。
ContextMenuStrip / 双击行为 右键或双击快速清空内容。
Post / Send 通过 SynchronizationContext 在 UI 线程更新。

Forms/Popups.cs

基础弹窗窗体,提供可拖动、Esc 关闭、Enter 执行动作的通用模板。

参数/属性 作用
OnMouseDown 调用 User32.ReleaseCapture/SendMessage 实现无边框拖动。
ProcessCmdKey 捕获 Esc 关闭、Enter 调用 DoEnter()
RectColor 自定义边框颜色,OnPaint 绘制轮廓。
DoEnter() 虚方法,子弹窗可覆写以执行"确认"逻辑。

Forms/Carousel.cs

轮播控件,支持图片/内容自动轮播、指示器、圆角、多状态外观,常用于首页轮播图或状态展示。

参数/属性 作用
ImageList 轮播图片集合,支持多图自动切换。
Appearances (CarouselAppearanceCollection) 多状态外观集合,每个状态可配置图片、文本、颜色。
Direction 轮播方向(水平/垂直)。
Interval 自动轮播间隔(毫秒),默认 1000ms。
AutoPlay 是否自动播放,鼠标悬停时可暂停。
Radius / FilletStyle 圆角配置,支持四角或局部圆角。
IndicatorStyle 指示器样式(点状/数字等)。
IndicatorColor / IndicatorActiveColor 指示器颜色与激活颜色。
IndicatorSize / IndicatorSpacing 指示器尺寸与间距。
SelectIndexChanged 选中项变更事件,参数为 CarouselItemEventArgs
CurrentIndex 当前显示的项索引。
HasImages 判断是否存在轮播图片。
Post() / Send() 实现 IContext,支持跨线程更新。

主题与事件

UIManagers/ThemeManager.cs

集中注册所有主题(蓝/红/自定义等 18+ 种),并提供 ThemeStyle 与具体 Theme 实例的映射和切换。

成员 作用
ThemeManager.Style / ActiveTheme 保存当前主题样式以及对应 Theme 实例。
Update(this ThemeStyle style) 切换主题并触发 ThemeChanged
ApplyTheme(Control) 递归应用主题到控件树,所有 HControl 派生控件可复用。
GetTheme<T>() / GetAvailableThemeStyles() 读取或创建特定主题类型、列出可用样式供配置界面使用。

Events/EventHelper.cs

全局事件总线,负责分发地址刷新、通讯重连、权限变化、消息输出、主题/地址偏移等事件。

事件 说明
OnValueChanged(Dictionary<int, Address>) PLC 扫描线程调用 Refresh() 后,HForm/HUserControl 等订阅更新控件。
OnMessageChanged(object, Color) HRichTextBox 等日志控件监听以输出彩色文本。
OnAddressOffsetChanged(short) HSwitch/HTextBoxOffsetEnabled 功能通过此事件批量平移地址。
OnRedirection / OnThemeChanged / OnCommunication 分别驱动界面跳转、主题切换、通讯句柄注入。

工厂与初始化系统

Factory.cs

窗体与控件实例的创建工厂,提供单例缓存、地址收集、重定向管理与程序集加载能力。

成员/方法 作用
Assembly 设置需要加载的程序集,自动扫描容器类型(Form/UserControl/Panel 等)并缓存到 typeCache
Plc / InitializePlc(IPlc) 全局 PLC 通讯句柄,初始化时调用 ReConnected()
addressCache LRU 缓存,按类型存储窗体/控件的地址集合,加速地址收集。
panelCache 按名称和索引缓存 Panel 控件,支持多界面共享同名画布。
addresses / ExtraAddress 当前活动地址列表与附加地址(需一直存在),支持线程安全访问。
GetInstance<T>(index, args) 获取或创建指定类型的实例,支持索引区分同类型多实例,带参构造。
RemoveInstance<T>() 从缓存中移除指定类型的实例。
AddOrUpdatePanel(Panel) 注册 Panel 到缓存,支持通过 HPanel.RedirctionIndexTag 区分索引。
AddExtraAddress(Address) / RemoveExtraAddress(Address) 管理附加地址集合,用于跨界面共享的地址。
LoadAssembly(Assembly) 加载程序集并提取容器类型,建立类型名称到类型的映射。
SaveAddressCacheToFile() / LoadAddressCacheFromFile() 持久化地址缓存到文件,程序退出时自动保存,启动时可加载。
InvokeHelper_OnRedirection() 处理 EventHelper.OnRedirection 事件,根据重定向名称创建/加载窗体或用户控件,更新地址列表。
UpdateAddress(Control) 深度遍历控件树,收集所有 IPlcEntity 的地址(含主地址、监视地址、范围地址等)。

Initialize.cs

窗体初始化辅助类,提供批量扫描与地址收集功能。

方法 作用
InitializeComponent() 遍历所有已加载的容器类型,创建实例、收集 Panel、提取地址并缓存。
InitializeComponent<T>() 仅初始化指定类型,适用于按需加载场景。
ProcessControlsIteratively(Control) 使用栈进行深度优先遍历,收集 Panel 控件与 IPlcEntity 地址,避免递归栈溢出。

类型转换器

Converters/AddressConverter.cs

Address 类型转换器,支持属性网格中地址的字符串编辑与对象转换。

方法 作用
CanConvertFrom(ITypeDescriptorContext, Type) 判断是否可从字符串转换。
ConvertFrom(ITypeDescriptorContext, CultureInfo, object) 将字符串解析为 Address 对象(支持序列化格式)。
ConvertTo(ITypeDescriptorContext, CultureInfo, object, Type) Address 转换为字符串表示。

Converters/AppearanceSettingConverter.cs

AppearanceSetting 的类型转换器,用于设计器属性编辑。

Converters/ComparisionTypeConverter.cs

ComparisionType 枚举的转换器,提供友好的显示名称。

Converters/IconInfoConverter.cs

IconInfo 的类型转换器,支持图标信息的序列化与反序列化。

Converters/PathConverter.cs

文件/文件夹路径的类型转换器,验证路径有效性。

Converters/PropertyConverter.cs

通用属性转换器,用于复杂对象的属性网格编辑。

Converters/ValueRangeConverter.cs

ValueRange 结构体的类型转换器,支持 "Minimum, Maximum" 格式的字符串编辑。

数据模型

Data/Address.cs

PLC 通讯地址的核心数据模型,封装软元件类型、索引、数据类型、小数位等。

属性 作用
SoftType 软元件类型枚举(M/D/X/Y/C/T 等),默认 M
Index 软元件索引号,默认 0。
DataType 数据类型(Bit/UInt16/Int16/UInt32/Int32/Single/Double/String),影响读写长度。
DecimalPlaces 小数位数,用于数值格式化。
Enabled 地址是否启用,未启用时不参与通讯。
NegationEnabled 是否取反,读取后对值进行逻辑取反。
Serialize() / Deserialize(string) 地址的序列化与反序列化,用于缓存持久化。
GetHashCode() 基于软元件类型、索引、数据类型的哈希,用于地址去重。

Data/ValueRange.cs

数值范围结构体,用于输入验证与阈值控制。

属性/方法 作用
Minimum / Maximum 最小值与最大值,设置时自动校验范围有效性。
IsEmpty 判断范围是否为空(0, 0)。
operator + / operator - 范围相加/相减运算。
Copy() 深拷贝范围对象。

Data/BorderDecorator.cs

边框装饰器,用于自绘边框的配置与绘制。

属性 作用
BorderColor / BorderWidth 边框颜色与宽度。
BorderPadding 边框内边距。
BorderEnabled 是否启用边框绘制。
SyncPaddingWithBorder 是否将边框宽度同步到控件的 Padding。

Data/Redirection.cs

界面重定向配置,描述跳转目标信息。

属性 作用
LoaderName 载体名称(Panel 名称)。
RedirectionName 目标界面名称(窗体或用户控件类型名)。
Index 索引,用于区分同名界面的不同实例。

Data/ThemeColor.cs

主题颜色枚举,定义主题系统的标准颜色槽位。

Data/ThemeStyle.cs

主题样式枚举,包含 Blue/Red/Green/Gray/Custom 等 18+ 种预设主题。

Data/ActionType.cs

控件动作类型枚举:Switch(切换)、Set(设值)、Increment(自增)、Decrement(自减)、DelaySet(延时设值)、Reset(复位)等。

Data/SoftType.cs

PLC 软元件类型枚举:M(内部继电器)、D(数据寄存器)、X(输入)、Y(输出)、C(计数器)、T(定时器)等。

Data/DataType.cs

数据类型枚举:Bit(位)、UInt16/Int16(16位字)、UInt32/Int32(32位双字)、Single(单精度浮点)、Double(双精度浮点)、String(字符串)等。

Data/FunctionCode.cs

Modbus 功能码枚举,用于通讯协议定义。

Data/OperationTable.cs

操作表基类,用于 HDataGridView 的数据绑定与列定义。

Data/ComboBoxItem.cs

下拉框项数据模型,支持值-文本映射。

Data/EntityUpdateData.cs

实体更新数据封装,用于批量更新场景。

Data/FillletStyle.cs

圆角样式枚举:All(四角)、Top(上角)、Bottom(下角)、Left(左角)、Right(右角)等。

Data/IndicatorStyle.cs

指示灯样式枚举。

Data/LineOrientation.cs

线条方向枚举:Horizontal(水平)、Vertical(垂直)。

Data/Native.cs

原生数据结构封装。

Data/NumberBase.cs

数值进制枚举。

Data/RollStyle.cs

滚动样式枚举:Left(向左)、Right(向右)、Up(向上)、Down(向下)。

Data/ScrollDirection.cs

滚动方向枚举。

Data/SoftIndex.cs

软元件索引辅助类。

设计时支持

Designs/Gradient.cs

渐变配置类,泛型设计支持不同控件类型。

属性 作用
Enabled 是否启用渐变。
Angle 渐变角度(0-360 度)。
StartColor / EndColor 起始与结束颜色。
Blend 颜色混合配置,支持多色渐变。
_owner 关联的控件引用,属性变化时触发 Invalidate()

Designs/Watermark.cs

水印配置类,用于文本框等控件的提示文字。

属性 作用
Content 水印文本内容。
ForeColor 水印文字颜色,默认灰色。
Font 水印字体。
_owner 关联控件,文本变化时重绘。

Designs/HControlAppearance.cs

控件外观统一配置,包含边框、鼠标状态等。

属性 作用
BorderSize / BorderColor 边框尺寸与颜色。
MouseOverBorderColor / MouseDownBorderColor 鼠标悬停/按下时的边框颜色。
IndicatorStyle 指示灯样式(用于边框指示效果)。

Designs/HControlDesigner.cs

HControl 的设计器基类,提供设计时行为扩展。

Designs/HButtonDesigner.cs

HButton 的专用设计器,优化按钮的设计时体验。

Designs/HLabelDesigner.cs

HLabel 的设计器。

Designs/HPanelDesigner.cs

HPanel 的设计器,支持容器控件的设计时编辑。

Designs/HPictureBoxDesigner.cs

HPictureBox 的设计器。

Designs/HComparisionButtonDesigner.cs

HComparisionButton 的设计器。

Designs/HRedirectionButtonDesigner.cs

HRedirectionButton 的设计器。

Designs/HUserControlDesigner.cs

HUserControl 的设计器,支持用户控件的设计时编辑。

Designs/CarouselDesigner.cs

Carousel 轮播控件的设计器。

Designs/HControlAdapter.cs

控件适配器基类,用于设计时行为扩展。

Designs/HLampAdapter.cs

HLamp 的适配器。

主题系统

Themes/Theme.cs

主题抽象基类,定义主题的通用接口与实现。

成员 作用
_themeStyleMap 静态 LRU 缓存,映射 ThemeStyle 到具体主题实例。
Name 主题样式名称(ThemeStyle 枚举值)。
GradientColors 主题渐变色数组,用于控件渐变配置。
appearance 主题的默认外观配置(HControlAppearance)。
InitializeThemeStyle(ThemeStyle) 初始化主题样式,设置默认外观。

Themes/BlueTheme.cs / RedTheme.cs / GreenTheme.cs

具体主题实现类(18+ 种),继承 Theme 并定义各自的颜色方案:

  • BlueTheme:蓝色主题
  • RedTheme:红色主题
  • GreenTheme:绿色主题
  • GrayTheme:灰色主题
  • CyanTheme:青色主题
  • GoldTheme:金色主题
  • LimeTheme:青柠色主题
  • MagentaTheme:洋红色主题
  • MaroonTheme:栗色主题
  • NavyTheme:海军蓝主题
  • OrangeTheme:橙色主题
  • PurpleTheme:紫色主题
  • SliverTheme:银色主题
  • YellowTheme:黄色主题
  • BlackTheme:黑色主题
  • WhiteTheme:白色主题
  • TransparentTheme:透明主题
  • CustomTheme:自定义主题
  • InheritedTheme:继承主题
  • BrokenColourTheme:故障色主题

每个主题类重写 GradientColorsappearance 以提供独特的视觉风格。

UI 类型编辑器

UITypeEditors/AddressEditor.cs

地址编辑器,提供可视化地址选择对话框。

方法 作用
GetEditStyle(ITypeDescriptorContext) 返回 Modal,以对话框形式编辑。
EditValue(ITypeDescriptorContext, IServiceProvider, object) 打开 AddressDialog,返回用户选择的地址。

UITypeEditors/FilePathEditor.cs

文件路径编辑器,通过文件对话框选择文件路径。

UITypeEditors/FolderPathEditor.cs

文件夹路径编辑器,通过文件夹对话框选择目录。

UITypeEditors/FilletEditor.cs

圆角编辑器,可视化配置控件的圆角参数。

UITypeEditors/IconPickerEditor.cs

图标选择器编辑器,打开图标拾取界面(IconPickerDropDownControl)选择字体图标。

类型描述提供程序

Provider/AppearanceFilteredTypeDescriptionProvider.cs

外观类型的属性过滤提供程序,用于在设计器中隐藏或显示特定属性。

成员 作用
AppearanceFilteredTypeDescriptionProvider<T> 泛型提供程序,可指定需要过滤的属性名数组。
GetTypeDescriptor() 返回自定义类型描述符,过滤指定属性。
AppearanceFilteredTypeDescription 内部类,实现属性过滤逻辑。

Provider/AppearanceSettingFilteredTypeDescriptionProvider.cs

AppearanceSetting 的属性过滤提供程序。

Provider/ButtonAppearanceFilteredTypeDescriptionProvider.cs

ButtonAppearance 的属性过滤提供程序。

Provider/RedirectionButtonAppearanceFilteredTypeDescriptionProvider.cs

RedirectionButtonAppearance 的属性过滤提供程序。

几何与绘图

Drawing/PointD.cs

双精度浮点坐标点结构体,用于高精度几何计算。

成员 作用
X / Y 坐标值(double)。
operator + / operator - 点运算。
DistanceTo(PointD) 计算两点间距离。

Drawing/SizeD.cs

双精度尺寸结构体。

属性 作用
Width / Height 宽度与高度(double)。

Drawing/RectangleD.cs

双精度矩形结构体。

属性 作用
X / Y / Width / Height 矩形位置与尺寸。
Location / Size 位置点与尺寸。
Contains(PointD) 判断点是否在矩形内。

Drawing/Circle.cs

圆形几何类,用于圆形控件的绘制与碰撞检测。

成员 作用
Center / Radius 圆心与半径。
Contains(PointD) 判断点是否在圆内。
GetBounds() 获取外接矩形。

Drawing/Ellipse.cs

椭圆几何类。

Drawing/Line.cs

线段几何类。

成员 作用
Start / End 起点与终点。
Length 线段长度。
Intersects(Line) 判断两线段是否相交。

Drawing/RotatedRectangle.cs

旋转矩形类,支持任意角度的矩形变换。

Drawing/ValueRange.cs

已在 Data/ValueRange.cs 中说明,此处为几何命名空间下的数值范围工具。

通讯接口与适配器

Interfaces/IPlc.cs

PLC 通讯接口,定义统一的读写操作。

成员 作用
Connected 连接状态。
SlaveAddress / IpAddress / Port Modbus 从站地址、IP 地址、端口号。
PortName / BaudRate / DataBits / Parity / StopBits 串口通讯参数。
ConnectedTimeout / ReadTimeout / WriteTimeout 连接、读取、写入超时(秒)。
Retry 重连次数。
Open() / Close() 打开/关闭连接。
WriteDevice(Address) / WriteDevice(Address, params object[]) 写入单个或批量值。
ReadDevice(out Address) / ReadDevice(Address, out object[]) 读取单个地址或连续地址。
ReadDeviceRandom(List<Address>, out Dictionary<int, Address>) 随机读取多个地址。
WriteDeviceRandom(List<Address>) 随机写入多个地址。

Interfaces/IPlcEntity.cs

PLC 实体接口,控件实现此接口以支持地址绑定。

属性 作用
Plc PLC 通讯句柄引用。
Address / MonitorAddress 主地址与监视地址。
MaximumAddress / MinimumAddress 动态范围地址。
IsAddressAvailable / IsMonitorAddressAvailable / IsRangeAddressAvailable 地址可用性判断。
Instance(IPlc) 注入 PLC 句柄。
Update() 根据 PLC 数据更新控件显示。

Interfaces/IAuthorityFilter.cs

权限过滤接口。

方法 作用
CheckAuthority(int src) 检查指定权限等级,返回是否通过。

Interfaces/ILock.cs

锁定接口。

方法 作用
CheckLock(bool locked) 检查是否锁定,返回是否允许操作。

Interfaces/IContext.cs

同步上下文接口,用于跨线程 UI 更新。

成员 作用
IsContainer 是否为容器控件。
Post(SendOrPostCallback, object) 异步分派到 UI 线程。
Send(SendOrPostCallback, object) 同步分派到 UI 线程。

Interfaces/IFillet.cs

圆角接口。

属性 作用
Radius 圆角半径。
FilletStyle 圆角样式。

Interfaces/ITheme.cs

主题接口。

方法 作用
ApplyTheme() 应用主题到控件。

Interfaces/IModbusMaster.cs

Modbus 主站接口,定义 Modbus 协议操作。

Interfaces/IModbusMessage.cs

Modbus 消息接口,封装 Modbus 通讯消息。

Interfaces/ISocket.cs

Socket 通讯接口。

Interfaces/IStreamResource.cs

流资源接口,用于串口/网络流的统一抽象。

IO/SerialPortAdapter.cs

串口适配器,实现 IPlc 接口,封装串口通讯逻辑。

功能 说明
串口参数配置 支持波特率、数据位、校验位、停止位配置。
连接管理 Open() / Close() 管理串口连接。
数据读写 实现 ReadDevice / WriteDevice 方法,通过串口与设备通讯。

IO/SocketAdapter.cs

Socket 适配器,实现 IPlc 接口,封装 TCP/IP 网络通讯。

功能 说明
网络参数配置 IP 地址、端口号、超时设置。
连接管理 TCP 连接的建立与断开。
数据读写 通过网络套接字实现设备通讯。

Devices/ModbusDevice.cs

Modbus 设备基类(当前为预留接口,具体实现可扩展)。

工具类

Utilities/NativeMethod.cs

Win32 API 封装与设计时辅助方法。

方法 作用
GenerateUniqueName(Type) 为控件生成唯一名称(设计时)。
InvalidateControl(Control) 安全地触发控件重绘。
SetCursor(Cursor) 设置鼠标光标。
Win32 封装 封装 User32Gdi32 等系统 API。

Utilities/Address.cs

Address 扩展方法。

方法 作用
Copy() 深拷贝地址对象。
ToString() 格式化地址字符串。
Equals(Address) 地址比较。

Utilities/Contains.cs

集合扩展方法,提供高效的包含判断。

Utilities/Image.cs

图像处理扩展方法。

方法 作用
Clone() 深拷贝图像,避免资源共享问题。
Resize(Size) 调整图像尺寸。

Utilities/HColors.cs

颜色计算工具。

方法 作用
Brighten(Color, float) 增亮颜色。
Darken(Color, float) 变暗颜色。
Blend(Color, Color, float) 颜色混合。

Utilities/ThemeStyleHelper.cs

主题样式辅助类。

方法 作用
GetDisplayName(ThemeStyle) 获取主题样式的显示名称。
ParseThemeStyle(string) 从字符串解析主题样式。

对话框

Dialogs/AddressDialog.cs

地址编辑对话框,继承 CommonDialog,提供标准化的地址选择界面。

成员 作用
EditedAddress 待编辑的地址对象,对话框关闭后返回用户编辑的结果。
Reset() 重置对话框状态,创建新的默认地址。
RunDialog(IntPtr) 显示 AddressEditorForm 并返回用户操作结果(OK/Cancel)。

事件与委托

Events/EventHelper.cs

全局事件总线,已在"主题与事件"章节详细说明。

Events/ThemeChangedEventArgs.cs

主题变更事件参数。

属性 作用
OldTheme 变更前的主题实例。
NewTheme 变更后的主题实例。

Events/CarouselItemEventArgs.cs

轮播项点击事件参数。

属性 作用
Index 被点击项的索引。
Appearance 被点击项的 CarouselAppearance 对象。

Delegates/Invokes.cs

全局事件委托定义文件,声明所有系统级事件的委托类型。

委托 作用
RedirectionEventHandler 界面重定向事件:(redirectionLoader, redirection, index)
AddressChangedEventHandler 地址列表变更事件:(List<Address> addresses)
ValueChangedEventHandler 地址值变更事件:(Dictionary<int, Address> addresses),键为地址哈希码。
RightsChangedEventHandler 权限变更事件:(object rights)
MessageChangedEventHandler 消息变更事件:(object message, Color color),用于日志输出。
CommumicationEventHandler 通讯句柄变更事件:(IPlc plc)
ThemeChangedEventHandler 主题样式变更事件:(ThemeStyle style)
AddressOffsetChangedEventHandler 地址偏移变更事件:(short offset),用于批量地址平移。

字体图标系统

Fonts/IconManager.cs

字体图标管理器,提供图标字体的加载、缓存、渲染与测量功能。

成员 作用
_fontCache LRU 缓存,按字体大小缓存 Font 对象,避免重复创建。
_fontFamily 图标字体家族(从内嵌资源加载)。
_measureCache 图标尺寸测量结果缓存(IconFontSizeKeySizeF)。
_renderCache 图标渲染结果缓存(IconRenderKeyBitmap),提升重复绘制性能。
IconFontReLoaded 字体重新加载事件。
Initialize() 从程序集资源加载字体文件(*.ttf*.fcp),注册到 PrivateFontCollection
GetIconInfo(int index) 根据索引获取 IconInfo 对象。
MeasureIcon(IconInfo, float) 测量图标在指定大小下的尺寸。
RenderIcon(IconInfo, float, Color) 渲染图标为位图,支持颜色定制。
Dispose() 释放所有缓存的字体与位图资源。

Fonts/IconInfo.cs

图标信息数据模型。

属性 作用
Index 图标索引(字符码点)。
Name 图标名称。
Description 图标描述。

Fonts/IconCollection.cs

图标集合类,管理所有可用图标。

Fonts/IconIndex.cs

图标索引枚举或常量定义。

Fonts/IconCell.cs

图标单元格类,用于图标选择器的网格显示。

Fonts/IconPickerDropDownControl.cs

图标选择下拉控件,提供图标拾取界面。

功能 说明
图标网格显示 以网格形式展示所有可用图标。
图标搜索 支持按名称搜索图标。
图标选择 点击图标后返回 IconInfo

Fonts/IconPickerGrid.cs

图标选择网格控件。

Fonts/IconPickerListBox.cs

图标选择列表框控件。

Fonts/IconRenderer.cs

图标渲染器,封装图标的绘制逻辑。

Fonts/IconRenderKey.cs

图标渲染键,用于缓存键的生成。

Fonts/IconFontSizeKey.cs

图标字体大小键,用于测量缓存的键生成。

Fonts/*.ttf / Fonts/*.fcp

内嵌字体文件:

  • Icons.ttf / Icons.fcp:自定义字体
  • Custom.ttf / Custom.fcp:自定义字体变体
  • HIcons.fcp:图标字体

相等性比较器

EqualityComparer/AddressEqualityComparer.cs

地址相等性比较器,实现 IEqualityComparer<Address>,用于地址集合的去重与查找。

方法 作用
Equals(Address, Address) 比较两个地址是否相等,基于软元件类型、有效索引、位索引、数据类型。
GetHashCode(Address) 计算地址的哈希码,用于字典与集合操作。

站点与工厂扩展

Sites/FakeSite.cs

假站点类,用于设计时或测试场景,模拟 ISite 接口。

组合控件与对话框

Forms/Composition/Input.cs

数值输入对话框,继承 Form,提供带范围验证的数值输入界面。

功能 说明
数值输入 支持整数/浮点数输入,可配置小数位。
范围验证 根据 ValueRange 限制输入范围。
键盘支持 Enter 确认、Esc 取消。
屏幕定位 自动计算并定位到合适屏幕位置。
拖动支持 无边框设计,支持拖动。

Forms/Composition/HMessageBox.cs

自定义消息框,继承 Popups,提供图标、标题、消息文本与按钮配置。

成员 作用
Show(string message, string title, MessageBoxIcon icon) 静态方法,显示消息框。
Show(string message, string title, MessageBoxButtons buttons) 支持多按钮配置(OK/NG/Cancel)。
pb_Icon 图标显示控件,根据 MessageBoxIcon 显示不同图标。
rtb_Message 消息文本显示,支持富文本。
btn_OK / btn_NG 确认/取消按钮,使用 HButton 控件。

Forms/Composition/AddressEditorForm.cs

地址编辑器窗体,配合 AddressDialog 使用,提供可视化的地址配置界面。

功能 说明
软元件选择 下拉框选择软元件类型(M/D/X/Y 等)。
索引输入 输入软元件索引号。
数据类型选择 选择数据类型(Bit/UInt16/Int16/UInt32/Int32/Single/Double/String)。
小数位配置 配置数值显示的小数位数。
取反选项 是否启用地址取反。
多语言支持 支持中文、英文、日文、韩文界面。

Forms/Composition/FilletControl.cs

圆角配置控件,用于设计器中可视化配置控件的圆角参数。

功能 说明
圆角半径设置 滑块或输入框设置圆角半径。
圆角样式选择 选择四角/上角/下角等样式。
实时预览 实时显示圆角效果。

Forms/Composition/HStatusForm.cs

状态窗体,用于显示系统状态或进度信息。

Forms/Composition/HUpDown.cs

上下调节控件,用于数值的增减操作。

Forms/Composition/LogManagement.cs

日志管理控件,提供日志查看、筛选、导出等功能。

Forms/Composition/StatisticsControl.cs

统计控件,用于数据统计与图表展示。

应用程序管理

Application.cs (App 类)

应用程序单例管理类,提供程序信息获取、单例控制、权限检查、性能监控等功能。

成员 作用
Instance 单例实例,使用 Singleton<App> 模式。
IsSingleton() 检查程序是否已运行(通过 Mutex),防止多实例。
IsRunAsAdmin() 检查当前是否以管理员权限运行。
RunAsAdmin() 以管理员权限重新启动程序。
WorkingDirectory 获取程序所在文件夹路径。
FileName 获取主程序文件完整路径。
Name 获取程序名称(不含扩展名)。
IconFileName 获取程序图标文件名。
DesktopDirectory 获取桌面文件夹路径。
StartUp 获取启动文件夹路径。
CreateShortcut(string targetPath, string shortcutPath) 创建桌面快捷方式。
CpuUsage / RamAvailable / DiskUsage / NetworkUsage / GpuUsage 性能计数器(.NET 4.0+),监控系统资源使用情况。
Dispose() 释放 Mutex 与性能计数器资源。

_using.cs

全局 using 指令集中定义文件,统一管理命名空间引用,简化代码。

Properties/

程序集属性与资源:

  • AssemblyInfo.cs:程序集信息(版本、公司、版权等)
  • Resources.resx:内嵌资源文件
  • Settings.settings:应用程序设置

其它模块说明

  • Sites/FakeSite.cs:假站点类,用于设计时或测试场景,模拟 ISite 接口。

使用建议

初始化流程

  1. 设置 Factory.Assembly 加载程序集。
  2. 调用 Factory.InitializePlc(IPlc) 注入通讯句柄。
  3. 调用 Factory.InitializeComponent() 初始化所有窗体并收集地址。
  4. 启动 PLC 通讯线程,定期调用 IPlc.ReadDeviceRandom() 并触发 EventHelper.OnValueChanged

主题切换

ThemeManager.Update(ThemeStyle.Blue); // 切换到蓝色主题

界面重定向

EventHelper.OnRedirection?.Invoke("MainPanel", "UserControl1", 0);

地址管理

var address = new Address { SoftType = SoftType.D, Index = 100, DataType = DataType.UInt16 };
Factory.AddExtraAddress(address); // 添加到附加地址

控件外观配置

在设计器中编辑 Appearances 集合,或通过代码:

button.Appearances.Add(new ButtonAppearance 
{ 
    State = 1, 
    BackColor = Color.Red, 
    Text = "运行" 
});

轮播控件使用

carousel.ImageList = imageList; // 设置图片列表
carousel.AutoPlay = true; // 启用自动播放
carousel.Interval = 2000; // 设置间隔 2 秒
carousel.Direction = ScrollDirection.Horizontal; // 水平轮播
carousel.SelectIndexChanged += (s, e) => 
{
    // 处理选中项变更
    var index = e.Index;
    var appearance = e.Appearance;
};

消息框使用

HMessageBox.Show("操作成功", "提示", MessageBoxIcon.Information);
HMessageBox.Show("确认删除?", "警告", MessageBoxButtons.OKCancel);

输入对话框使用

var input = new Input();
input.ValueRange = new ValueRange(0, 100); // 设置范围
input.DecimalPlaces = 2; // 小数位
if (input.ShowDialog() == DialogResult.OK)
{
    double value = input.Value;
}

单例程序控制

if (!App.Instance.IsSingleton().Content)
{
    MessageBox.Show("程序已在运行!");
    return;
}

管理员权限检查

if (!App.Instance.IsRunAsAdmin().Content)
{
    App.Instance.RunAsAdmin(); // 以管理员权限重启
    return;
}

快速开始指南

1. 基本项目设置

// Program.cs
static void Main()
{
    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);
    
    // 设置程序集
    Factory.Assembly = Assembly.GetExecutingAssembly();
    
    // 初始化 PLC 通讯
    var plc = new ModbusDevice(); // 或 SerialPortAdapter
    plc.IpAddress = "192.168.1.100";
    plc.Port = 502;
    Factory.InitializePlc(plc);
    
    // 初始化窗体
    Factory.InitializeComponent();
    
    // 启动主窗体
    Application.Run(new MainForm());
}

2. PLC 通讯线程

Task.Run(() =>
{
    while (true)
    {
        if (Factory.Plc?.Connected == true)
        {
            var addresses = Factory.Addresses?.ToList();
            if (addresses?.Count > 0)
            {
                if (Factory.Plc.ReadDeviceRandom(addresses, out var values) == 0)
                {
                    EventHelper.OnValueChanged?.Invoke(values);
                }
            }
        }
        Thread.Sleep(100); // 100ms 扫描周期
    }
});

3. 创建自定义控件

public class MyCustomControl : HControl
{
    public MyCustomControl()
    {
        // 设置默认外观
        Appearances.Add(new AppearanceSetting 
        { 
            State = 0, 
            BackColor = Color.White 
        });
    }
    
    protected override void OnPaint(PaintEventArgs e)
    {
        base.OnPaint(e);
        // 自定义绘制逻辑
    }
}

架构说明

核心模块关系

Factory (工厂)
  ├── InitializeComponent() → 扫描窗体 → 收集地址
  ├── PanelCache → 管理界面容器
  └── AddressCache → 缓存地址集合

EventHelper (事件总线)
  ├── OnValueChanged → 数据更新
  ├── OnRedirection → 界面跳转
  ├── OnThemeChanged → 主题切换
  └── OnCommunication → 通讯注入

ThemeManager (主题管理)
  ├── Theme (抽象基类)
  ├── BlueTheme / RedTheme 等 (具体主题)
  └── ApplyTheme() → 递归应用主题

IPlc (通讯接口)
  ├── ModbusDevice (Modbus 实现)
  ├── SerialPortAdapter (串口实现)
  └── SocketAdapter (网络实现)

数据流向

PLC 设备 
  → IPlc.ReadDeviceRandom() 
  → EventHelper.OnValueChanged 
  → HForm/HUserControl 订阅 
  → 控件 Update() 
  → UI 刷新

性能优化建议

  1. 地址缓存:使用 Factory.addressCache 避免重复扫描控件树。
  2. 图像资源:外观类自动 Clone 图像,避免资源共享问题,注意及时 Dispose。
  3. LRU 缓存:Factory 使用 LRU 缓存管理实例,自动清理不常用对象。
  4. 批量更新:通过 EventHelper.OnValueChanged 批量更新,减少 UI 刷新次数。
  5. 异步通讯:PLC 通讯应在独立线程,避免阻塞 UI。
  6. 主题应用:主题切换时使用 ThemeManager.ApplyTheme() 递归应用,避免逐个控件设置。

常见问题

Q: 控件在设计器中不显示?

A: 确保控件实现了 ICloneable,属性添加了 CategoryDescription,并注册了 Designer

Q: 地址读取失败?

A: 检查 Address.Enabled 是否为 trueFactory.Plc 是否已初始化并连接。

Q: 主题切换不生效?

A: 确保控件实现了 ITheme 接口,并在 ApplyTheme() 中正确更新外观。

Q: 界面重定向失败?

A: 检查目标类型是否已加载到 Factory.typeCache,Panel 名称是否正确注册。

Q: 内存泄漏?

A: 确保图像资源正确 Dispose,使用 using 语句或实现 IDisposable

扩展指南

添加新控件

  1. 继承 HControl 或合适的基类
  2. 实现必要的接口(IPlcEntityITheme 等)
  3. 定义对应的 Appearance 组件
  4. 创建 CollectionEditor(如需要)
  5. 注册 DesignerUITypeEditor(如需要)
  6. 在 README 中补充说明

添加新主题

  1. 继承 Theme 基类
  2. 重写 GradientColorsappearance
  3. ThemeManager 中注册
  4. 添加到 ThemeStyle 枚举

添加新通讯协议

  1. 实现 IPlc 接口
  2. 实现 ReadDevice / WriteDevice 方法
  3. 处理连接管理与错误重试
  4. 通过 Factory.InitializePlc() 注入

控件属性速查表

通用属性(所有 H 控件)

属性 类型 说明 默认值
Address Address PLC 通讯地址 null
Appearances AppearanceSettingCollection 多状态外观集合 空集合
Radius int 圆角半径 0
FilletStyle FilletStyle 圆角样式 All
Rights int 权限等级 0

HButton 特有属性

属性 类型 说明
ActionType ActionType 按钮动作类型(Switch/Set/Increment 等)
MonitorAddress Address 监视地址(与写入地址分离)
SetValue object 设值动作的目标值
NegationEnabled bool 是否启用取反
TouchEnabled bool 是否启用触摸支持

HTextBox 特有属性

属性 类型 说明
Watermark Watermark<HTextBox> 水印配置
BorderColor Color 边框颜色
BorderWidth int 边框宽度
TagVisible bool 是否显示 Tag 文本
AssociatedAddress Address 联动地址

HPanel/HPictureBox/HLabel 通用

属性 类型 说明
Gradient Gradient<T> 渐变配置
CurrentState int 当前状态值

设计器使用技巧

1. 外观集合编辑

  • 在属性窗口中点击 Appearances 右侧的 ... 按钮
  • 在集合编辑器中添加/删除/编辑外观项
  • 每个外观项可配置 StateTextBackColorForeColorImage
  • 支持拖拽排序

2. 地址配置

  • 点击 Address 属性右侧的 ... 按钮打开地址编辑器
  • 选择软元件类型(M/D/X/Y 等)
  • 输入索引号和数据类型
  • 配置小数位和取反选项

3. 圆角配置

  • 使用 FilletEditor 可视化配置圆角
  • 支持实时预览效果
  • 可单独配置四角样式

4. 渐变配置

  • Gradient 属性中启用渐变
  • 设置起始/结束颜色
  • 配置渐变角度(0-360 度)
  • 支持多色混合(Blend)

5. 图标选择

  • HIcon 控件的 Icon 属性中点击 ...
  • 在图标选择器中选择字体图标
  • 支持搜索和预览

6. 主题应用

  • 在设计器中右键控件选择"应用主题"
  • 或通过代码 ThemeManager.ApplyTheme(control) 应用

实际应用场景

场景 1:工业监控界面

// 创建监控面板
var panel = new HPanel
{
    Dock = DockStyle.Fill,
    Gradient = new Gradient<HPanel>
    {
        Enabled = true,
        StartColor = Color.FromArgb(240, 240, 240),
        EndColor = Color.FromArgb(255, 255, 255)
    }
};

// 添加状态指示灯
var lamp = new HLamp
{
    Location = new Point(10, 10),
    Size = new Size(50, 50),
    Address = new Address { SoftType = SoftType.M, Index = 100 }
};
lamp.Appearances.Add(new AppearanceSetting 
{ 
    State = 0, 
    BackColor = Color.Gray, 
    CenterBackColor = Color.DarkGray 
});
lamp.Appearances.Add(new AppearanceSetting 
{ 
    State = 1, 
    BackColor = Color.Green, 
    CenterBackColor = Color.Lime 
});

// 添加数值显示
var label = new HLabel
{
    Location = new Point(70, 10),
    Size = new Size(200, 30),
    Address = new Address 
    { 
        SoftType = SoftType.D, 
        Index = 100, 
        DataType = DataType.UInt16,
        DecimalPlaces = 2
    },
    TextAlign = ContentAlignment.MiddleLeft
};

panel.Controls.AddRange(new Control[] { lamp, label });

场景 2:参数设置界面

// 创建参数输入框
var textBox = new HTextBox
{
    Location = new Point(10, 10),
    Size = new Size(200, 30),
    Address = new Address { SoftType = SoftType.D, Index = 200 },
    Watermark = new Watermark<HTextBox>
    {
        Content = "请输入参数值",
        ForeColor = Color.Gray
    },
    MinimumValue = 0,
    MaximumValue = 1000,
    Rights = 1 // 需要权限等级 1
};

// 添加设置按钮
var btnSet = new HButton
{
    Location = new Point(220, 10),
    Size = new Size(80, 30),
    Text = "设置",
    ActionType = ActionType.Set,
    Address = new Address { SoftType = SoftType.D, Index = 200 },
    SetValue = 100,
    Rights = 1
};

场景 3:多页面导航

// 创建导航按钮组
var btnHome = new HRedirectionButton
{
    Text = "首页",
    Redirection = new Redirection 
    { 
        LoaderName = "MainPanel", 
        RedirectionName = "HomePage" 
    }
};

var btnSettings = new HRedirectionButton
{
    Text = "设置",
    Redirection = new Redirection 
    { 
        LoaderName = "MainPanel", 
        RedirectionName = "SettingsPage" 
    }
};

// 注册 Panel 容器
var mainPanel = new Panel { Name = "MainPanel", Dock = DockStyle.Fill };
Factory.AddOrUpdatePanel(mainPanel);

场景 4:报警滚动显示

var rollText = new HRollTextBox
{
    Dock = DockStyle.Top,
    Height = 30,
    RollStyle = RollStyle.Left,
    Speed = 2,
    Interval = 50,
    BackColor = Color.Red,
    ForeColor = Color.White
};

// 订阅报警地址变化
EventHelper.OnValueChanged += (addresses) =>
{
    var alarms = new List<string>();
    foreach (var addr in addresses.Values)
    {
        if (addr.SoftType == SoftType.M && addr.Index >= 1000 && addr.Index < 1100)
        {
            if (Convert.ToBoolean(addr.Value))
            {
                alarms.Add($"报警 {addr.Index - 1000}");
            }
        }
    }
    rollText.Source = string.Join(" | ", alarms);
};

场景 5:主题切换功能

// 创建主题选择下拉框
var cmbTheme = new ComboBox
{
    Dock = DockStyle.Top,
    DropDownStyle = ComboBoxStyle.DropDownList
};

// 填充主题列表
var themes = ThemeManager.GetAvailableThemeStyles();
foreach (var theme in themes)
{
    cmbTheme.Items.Add(ThemeStyleHelper.GetDisplayName(theme));
}
cmbTheme.SelectedIndex = 0;

// 主题切换事件
cmbTheme.SelectedIndexChanged += (s, e) =>
{
    var selectedTheme = themes[cmbTheme.SelectedIndex];
    ThemeManager.Update(selectedTheme);
};

调试与故障排除

启用调试日志

// 订阅消息事件查看调试信息
EventHelper.OnMessageChanged += (message, color) =>
{
    Console.WriteLine($"[{DateTime.Now:HH:mm:ss}] {message}");
    // 或输出到日志文件
    File.AppendAllText("debug.log", $"[{DateTime.Now}] {message}\r\n");
};

检查地址收集

// 初始化后检查地址
Factory.InitializeComponent();
var addresses = Factory.Addresses;
Console.WriteLine($"共收集到 {addresses?.Count ?? 0} 个地址");
foreach (var addr in addresses ?? new List<Address>())
{
    Console.WriteLine($"  {addr.SoftType}{addr.Index} - {addr.DataType}");
}

检查通讯连接

// 定期检查连接状态
var timer = new System.Windows.Forms.Timer { Interval = 1000 };
timer.Tick += (s, e) =>
{
    if (Factory.Plc != null)
    {
        labelStatus.Text = Factory.Plc.Connected ? "已连接" : "未连接";
        labelStatus.ForeColor = Factory.Plc.Connected ? Color.Green : Color.Red;
    }
};
timer.Start();

性能分析

// 使用 Stopwatch 测量性能
var sw = Stopwatch.StartNew();
Factory.InitializeComponent();
sw.Stop();
Console.WriteLine($"初始化耗时: {sw.ElapsedMilliseconds}ms");

// 检查缓存命中率
Console.WriteLine($"地址缓存数量: {Factory.addressCache?.Count ?? 0}");
Console.WriteLine($"实例缓存数量: {Factory.instanceCache?.Count ?? 0}");

版本历史

主要版本特性

  • v1.0+: 基础控件库,支持 PLC 通讯、多状态外观、主题系统
  • 支持 30+ 工业控件
  • 18+ 内置主题
  • 完整的设计时支持
  • Modbus/串口/网络通讯适配器

许可证

深圳市海蓝智能科技有限公司 © 2024-2025 保留所有权利。

API 快速参考

核心静态类

Factory(工厂类)
// 程序集管理
Factory.Assembly = Assembly.GetExecutingAssembly();
Factory.LoadAssembly(assembly);

// PLC 通讯
Factory.Plc = plc;
Factory.InitializePlc(plc);

// 实例管理
var form = Factory.GetInstance<MainForm>();
var form2 = Factory.GetInstance<MainForm>(index: 1); // 多实例
Factory.RemoveInstance<MainForm>();

// 地址管理
Factory.Addresses; // 当前活动地址
Factory.ExtraAddress; // 附加地址
Factory.AddExtraAddress(address);
Factory.RemoveExtraAddress(address);

// Panel 管理
Factory.AddOrUpdatePanel(panel);

// 初始化
Factory.InitializeComponent();
Factory.InitializeComponent<MainForm>(); // 仅初始化指定类型
EventHelper(事件总线)
// 订阅事件
EventHelper.OnValueChanged += (addresses) => { /* 处理数据更新 */ };
EventHelper.OnRedirection += (loader, name, index) => { /* 处理界面跳转 */ };
EventHelper.OnThemeChanged += (style) => { /* 处理主题切换 */ };
EventHelper.OnCommunication += (plc) => { /* 处理通讯注入 */ };
EventHelper.OnMessageChanged += (msg, color) => { /* 处理消息输出 */ };
EventHelper.OnAddressOffsetChanged += (offset) => { /* 处理地址偏移 */ };

// 触发事件
EventHelper.OnValueChanged?.Invoke(addresses);
EventHelper.OnRedirection?.Invoke("MainPanel", "UserControl1", 0);
ThemeManager(主题管理)
// 切换主题
ThemeManager.Update(ThemeStyle.Blue);

// 获取当前主题
var currentTheme = ThemeManager.ActiveTheme;
var currentStyle = ThemeManager.Style;

// 应用主题到控件
ThemeManager.ApplyTheme(control);

// 获取可用主题
var themes = ThemeManager.GetAvailableThemeStyles();

// 获取特定主题实例
var blueTheme = ThemeManager.GetTheme<BlueTheme>();
App(应用程序管理)
// 单例检查
if (!App.Instance.IsSingleton().Content)
{
    // 程序已运行
}

// 权限检查
if (!App.Instance.IsRunAsAdmin().Content)
{
    App.Instance.RunAsAdmin();
}

// 路径获取
var dir = App.Instance.WorkingDirectory.Content;
var name = App.Instance.Name.Content;

常用扩展方法

Address 扩展
address.Copy(); // 深拷贝
address.Serialize(); // 序列化为字符串
Address.Deserialize(str); // 反序列化
address.IsDefault(); // 判断是否为默认地址
集合扩展
list.DistinctAndSort(); // 去重并排序
list.DistinctAndSortInPlace(); // 原地去重排序
list.Copy(); // 深拷贝
图像扩展
image.Clone(); // 深拷贝图像
颜色扩展
color.Brighten(0.2f); // 增亮 20%
color.Darken(0.2f); // 变暗 20%
HColors.Blend(color1, color2, 0.5f); // 混合颜色

最佳实践

1. 地址管理

// ✅ 推荐:使用 Enabled 属性控制地址是否参与通讯
address.Enabled = true;

// ✅ 推荐:使用 ExtraAddress 管理全局共享地址
Factory.AddExtraAddress(globalAddress);

// ❌ 不推荐:直接修改 Addresses 集合
// Factory.addresses.Add(address); // 错误

2. 资源管理

// ✅ 推荐:使用 using 语句管理图像资源
using (var image = new Bitmap("icon.png"))
{
    appearance.Image = image.Clone(); // 自动 Clone
}

// ✅ 推荐:实现 IDisposable 释放资源
public class MyControl : HControl, IDisposable
{
    public void Dispose()
    {
        // 释放图像资源
        foreach (var app in Appearances)
        {
            app.Image?.Dispose();
        }
    }
}

3. 线程安全

// ✅ 推荐:使用 Post/Send 进行跨线程更新
control.Post(() => {
    control.Text = "更新后的文本";
});

// ✅ 推荐:在通讯线程中使用 EventHelper 分发数据
Task.Run(() => {
    var values = ReadFromPLC();
    EventHelper.OnValueChanged?.Invoke(values);
});

4. 事件订阅

// ✅ 推荐:在适当的地方取消订阅,避免内存泄漏
EventHelper.OnValueChanged += HandleValueChanged;
// ...
EventHelper.OnValueChanged -= HandleValueChanged;

// ✅ 推荐:使用弱事件或检查对象是否已释放
private void HandleValueChanged(Dictionary<int, Address> addresses)
{
    if (this.IsDisposed) return;
    // 处理逻辑
}

5. 性能优化

// ✅ 推荐:批量更新而非逐个更新
var addresses = Factory.Addresses?.ToList();
if (addresses?.Count > 0)
{
    plc.ReadDeviceRandom(addresses, out var values);
    EventHelper.OnValueChanged?.Invoke(values); // 一次触发,所有控件更新
}

// ✅ 推荐:使用缓存避免重复计算
if (!addressCache.TryGetValue(type, out var cached))
{
    cached = CollectAddresses(type);
    addressCache.TryAdd(type, cached);
}

注意事项

1. 设计时 vs 运行时

  • 设计时:控件在设计器中,某些属性可能为 null,需要检查
  • 运行时:确保在 LoadShown 事件中初始化运行时逻辑
protected override void OnLoad(EventArgs e)
{
    base.OnLoad(e);
    if (!DesignMode)
    {
        // 运行时初始化
        Factory.Plc?.Instance(this);
    }
}

2. 序列化

  • 所有外观组件都应实现 ISerializable 或使用 [Serializable]
  • 图像资源需要特殊处理,避免序列化大对象

3. 线程模型

  • UI 更新必须在 UI 线程
  • PLC 通讯应在后台线程
  • 使用 Post/SendInvoke/BeginInvoke 进行线程切换

4. 内存管理

  • 图像资源要及时 Dispose
  • 事件订阅要及时取消
  • 使用 using 语句管理资源

5. 异常处理

// ✅ 推荐:在关键操作中添加异常处理
try
{
    Factory.InitializeComponent();
}
catch (Exception ex)
{
    EventHelper.OnMessageChanged?.Invoke($"初始化失败: {ex.Message}", Color.Red);
    // 记录日志
}

代码示例集合

示例 1:完整的 PLC 监控应用

public partial class MainForm : HForm
{
    public MainForm()
    {
        InitializeComponent();
        InitializePLC();
        SetupUI();
    }

    private void InitializePLC()
    {
        var plc = new ModbusDevice
        {
            IpAddress = "192.168.1.100",
            Port = 502,
            SlaveAddress = 1,
            ConnectedTimeout = 30,
            ReadTimeout = 30,
            WriteTimeout = 30
        };
        
        if (plc.Open() == 0)
        {
            Factory.InitializePlc(plc);
            StartCommunicationThread();
        }
    }

    private void StartCommunicationThread()
    {
        Task.Run(() =>
        {
            while (Factory.Plc?.Connected == true)
            {
                try
                {
                    var addresses = Factory.Addresses?.ToList();
                    if (addresses?.Count > 0)
                    {
                        if (Factory.Plc.ReadDeviceRandom(addresses, out var values) == 0)
                        {
                            EventHelper.OnValueChanged?.Invoke(values);
                        }
                    }
                }
                catch (Exception ex)
                {
                    EventHelper.OnMessageChanged?.Invoke($"通讯错误: {ex.Message}", Color.Red);
                }
                Thread.Sleep(100);
            }
        });
    }

    private void SetupUI()
    {
        // 订阅数据更新
        EventHelper.OnValueChanged += OnDataUpdated;
        
        // 订阅消息
        EventHelper.OnMessageChanged += (msg, color) =>
        {
            richTextBoxLog.AppendText($"[{DateTime.Now:HH:mm:ss}] {msg}\r\n", color);
        };
    }

    private void OnDataUpdated(Dictionary<int, Address> addresses)
    {
        // 数据更新处理
        this.Post(() =>
        {
            // UI 更新逻辑
        });
    }
}

示例 2:动态主题切换

public class ThemeSelector : UserControl
{
    private ComboBox cmbTheme;
    
    public ThemeSelector()
    {
        InitializeComponent();
        LoadThemes();
        SubscribeThemeChanged();
    }

    private void LoadThemes()
    {
        cmbTheme.Items.Clear();
        var themes = ThemeManager.GetAvailableThemeStyles();
        foreach (var theme in themes)
        {
            cmbTheme.Items.Add(new ThemeItem
            {
                Style = theme,
                DisplayName = ThemeStyleHelper.GetDisplayName(theme)
            });
        }
        
        // 设置当前主题
        var current = themes.FirstOrDefault(t => t == ThemeManager.Style);
        if (current != ThemeStyle.None)
        {
            cmbTheme.SelectedItem = cmbTheme.Items.Cast<ThemeItem>()
                .FirstOrDefault(i => i.Style == current);
        }
    }

    private void SubscribeThemeChanged()
    {
        cmbTheme.SelectedIndexChanged += (s, e) =>
        {
            if (cmbTheme.SelectedItem is ThemeItem item)
            {
                ThemeManager.Update(item.Style);
            }
        };
    }

    private class ThemeItem
    {
        public ThemeStyle Style { get; set; }
        public string DisplayName { get; set; }
        public override string ToString() => DisplayName;
    }
}

示例 3:权限控制系统

public class AuthorityManager : IAuthorityFilter
{
    private int currentRights = 0;
    
    public bool CheckAuthority(int requiredRights)
    {
        return currentRights >= requiredRights;
    }

    public void SetRights(int rights)
    {
        currentRights = rights;
        EventHelper.OnRightsChanged?.Invoke(rights);
    }
}

// 使用
var authManager = new AuthorityManager();
authManager.SetRights(2); // 设置权限等级为 2

// 控件自动检查权限
button.Rights = 1; // 需要权限等级 1
textBox.Rights = 2; // 需要权限等级 2

高级配置示例

地址配置详解

基本地址配置
// 位地址(M100)
var bitAddress = new Address
{
    SoftType = SoftType.M,      // 软元件类型:M=内部继电器
    Index = 100,                 // 索引号
    DataType = DataType.Bit,    // 数据类型:Bit=位
    Enabled = true               // 启用地址
};

// 字地址(D100)- 16位
var wordAddress = new Address
{
    SoftType = SoftType.D,       // 软元件类型:D=数据寄存器
    Index = 100,
    DataType = DataType.UInt16,  // 数据类型:UInt16=无符号16位字,或使用 Int16=有符号16位字
    DecimalPlaces = 2,            // 小数位数:2位
    Enabled = true
};

// 双字地址(D100-D101)- 32位
var dwordAddress = new Address
{
    SoftType = SoftType.D,
    Index = 100,
    DataType = DataType.UInt32,  // 数据类型:UInt32=无符号32位双字,或使用 Int32=有符号32位双字
    DecimalPlaces = 3,
    Enabled = true
};
地址取反
var negatedAddress = new Address
{
    SoftType = SoftType.M,
    Index = 200,
    DataType = DataType.Bit,
    NegationEnabled = true  // 启用取反:读取值会自动取反(0变1,1变0)
};
动态范围地址
var textBox = new HTextBox
{
    Address = new Address { SoftType = SoftType.D, Index = 300 },
    // 动态范围:从 PLC 读取上下限
    MinimumAddress = new Address { SoftType = SoftType.D, Index = 301 },
    MaximumAddress = new Address { SoftType = SoftType.D, Index = 302 },
    // 或使用固定范围
    MinimumValue = 0,
    MaximumValue = 1000
};
地址序列化与反序列化
// 序列化地址为字符串
var address = new Address { SoftType = SoftType.D, Index = 100 };
string serialized = address.Serialize();
// 结果:"D,100,UInt16,0,False,True"

// 反序列化字符串为地址
Address deserialized = Address.Deserialize(serialized);

渐变配置详解

基本渐变
var panel = new HPanel
{
    Gradient = new Gradient<HPanel>
    {
        Enabled = true,
        StartColor = Color.Blue,
        EndColor = Color.Cyan,
        Angle = 90  // 90度=垂直渐变,0度=水平渐变
    }
};
多色渐变(Blend)
var panel = new HPanel
{
    Gradient = new Gradient<HPanel>
    {
        Enabled = true,
        StartColor = Color.Red,
        EndColor = Color.Blue,
        Angle = 45,
        Blend = new ColorBlend
        {
            Colors = new[] { Color.Red, Color.Yellow, Color.Green, Color.Blue },
            Positions = new[] { 0f, 0.33f, 0.66f, 1f }
        }
    }
};

圆角配置详解

四角圆角
var button = new HButton
{
    Radius = 10,
    FilletStyle = FilletStyle.All  // 四角都圆角
};
局部圆角
var button = new HButton
{
    Radius = 10,
    FilletStyle = FilletStyle.Top  // 仅上角圆角
    // 可选:Top, Bottom, Left, Right
};

外观集合高级用法

动态添加外观
var button = new HButton();

// 方法1:使用 Add 方法
button.Appearances.Add(new ButtonAppearance
{
    State = 0,
    Text = "停止",
    BackColor = Color.Gray
});

// 方法2:使用集合初始化器
button.Appearances = new ButtonAppearanceCollection
{
    new ButtonAppearance { State = 0, Text = "停止", BackColor = Color.Gray },
    new ButtonAppearance { State = 1, Text = "运行", BackColor = Color.Green }
};

// 方法3:通过索引访问
var appearance = button.Appearances.GetAppearanceSetting(0);
if (appearance != null)
{
    appearance.BackColor = Color.Blue;
    button.Invalidate(); // 刷新显示
}
外观克隆
var sourceAppearance = new ButtonAppearance
{
    State = 0,
    Text = "源外观",
    BackColor = Color.Red
};

// 克隆外观(避免引用共享)
var clonedAppearance = sourceAppearance.Copy();
clonedAppearance.State = 1;
clonedAppearance.Text = "克隆外观";

事件处理详解

数据更新事件
// 订阅全局数据更新事件
EventHelper.OnValueChanged += (addresses) =>
{
    // addresses: Dictionary<int, Address>,键为地址哈希码
    foreach (var kvp in addresses)
    {
        var address = kvp.Value;
        var hashCode = kvp.Key;
        
        // 根据地址类型处理
        if (address.SoftType == SoftType.M && address.Index == 100)
        {
            // 处理特定地址的数据更新
            bool value = Convert.ToBoolean(address.Value);
            UpdateUI(value);
        }
    }
};
界面重定向事件
// 触发界面重定向
EventHelper.OnRedirection?.Invoke(
    "MainPanel",        // Panel 名称
    "SettingsPage",     // 用户控件类型名
    0                   // 索引
);

// 订阅重定向事件(如果需要额外处理)
EventHelper.OnRedirection += (loader, name, index) =>
{
    // 自定义处理逻辑
    Log($"跳转到: {name} (索引: {index})");
};
主题切换事件
// 订阅主题切换事件
EventHelper.OnThemeChanged += (style) =>
{
    // 主题切换后的处理
    Log($"主题已切换为: {ThemeStyleHelper.GetDisplayName(style)}");
    
    // 可以保存主题设置
    Properties.Settings.Default.Theme = style.ToString();
    Properties.Settings.Default.Save();
};
消息输出事件
// 订阅消息事件(用于日志输出)
EventHelper.OnMessageChanged += (message, color) =>
{
    // 输出到日志控件
    if (richTextBoxLog != null)
    {
        richTextBoxLog.AppendText(
            $"[{DateTime.Now:HH:mm:ss}] {message}\r\n", 
            color != default ? color : Color.Black
        );
    }
    
    // 或输出到控制台
    Console.WriteLine($"[{DateTime.Now:HH:mm:ss}] {message}");
};

// 触发消息
EventHelper.OnMessageChanged?.Invoke("操作成功", Color.Green);
EventHelper.OnMessageChanged?.Invoke("操作失败", Color.Red);

PLC 通讯配置详解

Modbus TCP 配置
var modbus = new ModbusDevice
{
    IpAddress = "192.168.1.100",
    Port = 502,
    SlaveAddress = 1,
    ConnectedTimeout = 30,  // 连接超时(秒)
    ReadTimeout = 30,       // 读取超时(秒)
    WriteTimeout = 30,      // 写入超时(秒)
    Retry = 3              // 重试次数
};

// 打开连接
int result = modbus.Open();
if (result == 0)
{
    Factory.InitializePlc(modbus);
    EventHelper.OnMessageChanged?.Invoke("PLC 连接成功", Color.Green);
}
else
{
    EventHelper.OnMessageChanged?.Invoke($"PLC 连接失败: {result}", Color.Red);
}
串口通讯配置
var serialPort = new SerialPortAdapter
{
    PortName = "COM3",
    BaudRate = 9600,
    DataBits = 8,
    Parity = Parity.None,
    StopBits = StopBits.One,
    SlaveAddress = 1
};

// 打开连接
int result = serialPort.Open();
if (result == 0)
{
    Factory.InitializePlc(serialPort);
}
批量读取地址
// 获取所有需要读取的地址
var addresses = Factory.Addresses?.ToList();
if (addresses?.Count > 0)
{
    // 随机读取(高效)
    if (Factory.Plc.ReadDeviceRandom(addresses, out var values) == 0)
    {
        // 触发数据更新事件
        EventHelper.OnValueChanged?.Invoke(values);
    }
}
批量写入地址
var addresses = new List<Address>
{
    new Address { SoftType = SoftType.D, Index = 100, Value = 100 },
    new Address { SoftType = SoftType.D, Index = 101, Value = 200 },
    new Address { SoftType = SoftType.M, Index = 100, Value = true }
};

// 随机写入
int result = Factory.Plc.WriteDeviceRandom(addresses);
if (result == 0)
{
    EventHelper.OnMessageChanged?.Invoke("批量写入成功", Color.Green);
}

主题自定义详解

创建自定义主题
public class MyCustomTheme : Theme
{
    public MyCustomTheme()
    {
        InitializeThemeStyle(ThemeStyle.Custom);
        
        // 设置渐变色
        GradientColors = new[]
        {
            Color.FromArgb(100, 150, 200),
            Color.FromArgb(150, 200, 250),
            Color.FromArgb(200, 250, 255)
        };
        
        // 设置默认外观
        appearance.BorderColor = Color.FromArgb(100, 150, 200);
        appearance.BorderSize = 2;
    }
}

// 注册主题
ThemeManager._themeStyleMap.TryAdd(ThemeStyle.Custom, new MyCustomTheme());
应用主题到特定控件
// 应用主题到单个控件
ThemeManager.ApplyTheme(button);

// 应用主题到控件树
ThemeManager.ApplyTheme(mainForm);

// 递归应用(自动处理子控件)
private void ApplyThemeRecursive(Control control)
{
    if (control is ITheme themeControl)
    {
        themeControl.ApplyTheme();
    }
    
    foreach (Control child in control.Controls)
    {
        ApplyThemeRecursive(child);
    }
}

权限系统详解

实现权限过滤器
public class MyAuthorityFilter : IAuthorityFilter
{
    private int currentLevel = 0;
    
    public bool CheckAuthority(int requiredLevel)
    {
        return currentLevel >= requiredLevel;
    }
    
    public void SetLevel(int level)
    {
        currentLevel = level;
        EventHelper.OnRightsChanged?.Invoke(level);
    }
}

// 使用
var authFilter = new MyAuthorityFilter();
authFilter.SetLevel(2); // 设置权限等级为 2

// 控件自动检查权限
button.Rights = 1;  // 需要等级 1,可以通过
textBox.Rights = 3; // 需要等级 3,当前等级 2,无法操作
锁屏系统
public class MyLock : ILock
{
    private bool isLocked = false;
    
    public bool CheckLock(bool locked)
    {
        return !isLocked || !locked;
    }
    
    public void SetLock(bool locked)
    {
        isLocked = locked;
    }
}

// 使用
var lockSystem = new MyLock();
lockSystem.SetLock(true);  // 锁定系统
// 所有控件的写入操作将被阻止

地址偏移功能

启用地址偏移
var textBox = new HTextBox
{
    Address = new Address { SoftType = SoftType.D, Index = 100 },
    OffsetEnabled = true  // 启用地址偏移
};

// 触发地址偏移(所有启用偏移的控件地址都会变化)
EventHelper.OnAddressOffsetChanged?.Invoke(50);
// 原地址 D100 变为 D150

工厂模式高级用法

按需加载窗体
// 仅初始化指定类型的窗体
Factory.InitializeComponent<MainForm>();

// 获取窗体实例(自动创建或从缓存获取)
var form = Factory.GetInstance<MainForm>();
var form2 = Factory.GetInstance<MainForm>(index: 1); // 多实例支持

// 移除实例
Factory.RemoveInstance<MainForm>();
地址缓存管理
// 保存地址缓存到文件
Factory.SaveAddressCacheToFile();

// 从文件加载地址缓存
Factory.LoadAddressCacheFromFile();

// 手动管理附加地址
Factory.AddExtraAddress(new Address { SoftType = SoftType.D, Index = 9999 });
Factory.RemoveExtraAddress(address);
Factory.ClearExtraAddress();

技术支持

如有问题或建议,请联系开发团队或提交 Issue。


如需扩展更多组件,请参考上述模式:定义 Component、实现 ICloneable、在属性上添加 DefaultValue/Category/Description 以确保设计器可用,并在 README 中补充新的文件说明。

Product Compatible and additional computed target framework versions.
.NET Framework net47 is compatible.  net471 is compatible.  net472 was computed.  net48 is compatible.  net481 is compatible. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.
  • .NETFramework 4.7

  • .NETFramework 4.7.1

  • .NETFramework 4.8

  • .NETFramework 4.8.1

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
2026.6.12.959 88 6/12/2026
2026.6.2.859 101 6/8/2026
2026.5.29.905 112 5/29/2026
2026.4.15.1112 121 4/15/2026
2026.4.13.1111 111 4/13/2026
2026.4.9.1135 103 4/13/2026
2026.3.17.1737 112 3/27/2026
2025.5.7.1007 206 5/7/2025
2025.4.29.1133 214 4/29/2025
2025.2.18.1652 160 2/26/2025

将Hi.Ltd类库里关于控件的跨线程方法移植到窗体控件库中