Hi.Ltd.Windows 2026.7.11.1653

dotnet add package Hi.Ltd.Windows --version 2026.7.11.1653
                    
NuGet\Install-Package Hi.Ltd.Windows -Version 2026.7.11.1653
                    
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.7.11.1653" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Hi.Ltd.Windows" Version="2026.7.11.1653" />
                    
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.7.11.1653
                    
#r "nuget: Hi.Ltd.Windows, 2026.7.11.1653"
                    
#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.7.11.1653
                    
#: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.7.11.1653
                    
Install as a Cake Addin
#tool nuget:?package=Hi.Ltd.Windows&version=2026.7.11.1653
                    
Install as a Cake Tool

Hi.Ltd.Windows

库简介

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

Result 错误链与版本说明

2026.6.30 起,对外业务 API 统一返回 Hi.Ltd 基础库的 Result / Result<T> / Task<Result> / Task<Result<T>>,用于错误链追溯;类库内部不主动写日志,失败信息经 Result 传出,由消费方自行决定是否调用 .Error()、持久化或弹窗提示。

错误链传播约定

场景 写法
包装上游失败 return Error.Result(nameof(x), upstreamResult)
直接透传 return upstreamResult
叶子异常 return Error.Result(ex)Error.Argument(nameof(p))
禁止 只传 .Message、返回 false/默认值吞掉上游、业务路径中无必要 throw

与旧版用法兼容(隐式解包)

Result<T>隐式转换为 T(Hi.Ltd 基础库):成功时得到 Content,失败时得到 default(引用类型为 null),不会抛异常。因此多数旧代码几乎不用改逻辑,只需把原先推断为 Tvar 改成显式类型即可恢复旧写法;需要错误链时再保留 Result 并检查 Successed

旧版(返回 T 升级后仍兼容的写法 说明
var form = Factory.GetInstance<MainForm>(); MainForm form = Factory.GetInstance<MainForm>(); var 会推断为 Result<MainForm>,需显式类型触发隐式转换
var theme = ThemePersistence.TryLoad(); ThemeStyle theme = ThemePersistence.TryLoad(); 同上
var addr = Address.Deserialize(s); Address addr = Address.Deserialize(s); 同上
Factory.LoadAssembly(path); Factory.LoadAssembly(path); 返回 Result 时可忽略返回值,与旧 void 用法一致
需要处理失败 var r = Factory.GetInstance<MainForm>(); + Successed / Error() 显式使用 Result 能力
// 旧版等价(最小改动:var → 显式类型)
MainForm form = Factory.GetInstance<MainForm>();
Application.Run(form);

ThemeStyle theme = ThemePersistence.TryLoad();
ThemeManager.Update(theme);

// 需要错误链时再显式检查(推荐用于库内/可恢复流程)
var formResult = Factory.GetInstance<MainForm>();
if (!formResult.Successed)
    return Error.Result(nameof(Factory.GetInstance), formResult);
Application.Run(formResult.Content);

// 先存 Result,失败时可选记录,用时再隐式转 T
var r = Factory.GetInstance<MainForm>();
if (!r.Successed) r.Error(); // 可选
MainForm form2 = r;

消费方示例

// 主题加载
var loadResult = ThemePersistence.TryLoad();
if (!loadResult.Successed)
{
    loadResult.Error();              // 可选:由应用决定是否记录
    ThemeManager.Update(ThemeStyle.Blue); // 或显式回退
    return;
}
ThemeManager.Update(loadResult.Content);

// 工厂实例(与旧版等价:显式类型即可)
MainForm form = Factory.GetInstance<MainForm>();
Application.Run(form);

// 或显式检查错误链
var formResult = Factory.GetInstance<MainForm>();
if (!formResult.Successed)
    return Error.Result(nameof(Factory.GetInstance), formResult);
Application.Run(formResult.Content);

版本与 NuGet 升级

  • 含 Result 迁移的版本尚未上传到 NuGet 源;是否升级由项目自行决定。
  • 未升级的项目:继续引用旧版包,API 与行为不变,不受本次改动影响。
  • 升级后:签名改为 Result / Result<T>,但借助隐式转换,多数调用点只需把 var 改成显式类型(见上表);voidResult 的 API 可继续忽略返回值。仅在你需要错误链传播或失败回退时才改为检查 Successed
  • 静态构造加载主题失败时,可通过 ThemeManager.InitialThemeLoadResult 查询完整错误链。

主要签名变更(升级时对照)

区域 旧签名(示意) 新签名
Factory T GetInstance<T>() Result<T> GetInstance<T>()(可隐式转为 T,失败为 default
Factory void LoadAssembly / InitializePlc Result
ThemePersistence ThemeStyle TryLoad() Result<ThemeStyle> TryLoad()
ThemePersistence void Save(...) Result Save(...)
Address Address Deserialize(string) Result<Address> Deserialize(string)
IPlcEntity void Instance / Update Result Instance / Update
Localization void InitializeLocalization Result / Result<T>
MessagePresentationHub DialogResult Present(...) Result<DialogResult> Present(...)

豁免(仍可不返回 Result)

  • UI 展示终端 API(MessagesHTipsHNotification 等 void 展示方法)
  • WinForms 重写(OnPaint/WndProc)、IList 集合、TypeConverter/UITypeEditor、P/Invoke
  • 可设计属性 get/set、事件声明、纯颜色/枚举判断

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 // 重定向索引
};
var addPanelResult = Factory.AddOrUpdatePanel(containerPanel);
if (!addPanelResult.Successed)
    addPanelResult.Error(); // 可选:由应用决定是否记录

AddOrUpdatePanel 返回 Result;失败时通过 InnerResult 可追溯原因,类库内部不自动写日志。

状态图片切换
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 initResult = Factory.InitializeLocalization("Resources");
if (!initResult.Successed)
    initResult.Error(); // 可选

// 切换语言
var cultureResult = Factory.ChangeCulture("zh-CN");
if (!cultureResult.Successed)
    return cultureResult;
绑定控件本地化
// 手动绑定单个控件
button.BindLocalization("Form.Button.Start", "Text");
label.BindLocalization("Form.Label.Temperature");

// 智能绑定(自动检测控件类型)
textBox.SmartBindLocalization("Form.TextBox.Input");

// 自动绑定容器内所有控件
this.AutoBindLocalization();
获取本地化字符串
var textResult = Factory.GetLocalizedString("Common.Ok");
if (textResult.Successed)
    label.Text = textResult.Content;
本地化资源配置
// 配置翻译引擎(如果使用 Hi.Ltd.LocalResource)
LocalResourceConfig.ApiKey = "your-api-key";
LocalResourceConfig.SecretKey = "your-secret-key";
LocalResourceConfig.EngineType = TranslateEngineType.MicrosoftEngine;

// 同步配置
LocalResourceConfig.SyncToLocalResource();

跨线程操作

安全更新控件
// 使用 Invoked 工具类进行跨线程操作
using Hi.Ltd.Threading;

// 从后台线程更新控件文本
this.textBox1.UpdateAction(args => 
{
    if (args?.Length > 0)
        this.textBox1.Text = args[0].ToString();
}, null, "新文本");

// 批量添加子控件
this.panel1.Add(new[] { button1, button2, button3 }, DockStyle.Top);

HCurve - 实时曲线控件

基本曲线
var curve = new HCurve
{
    Dock = DockStyle.Fill,
    BufferCapacity = 500,       // 环形缓冲容量
    AutoIncrementX = true,      // X 轴自动递增
    AutoScaleY = true,          // Y 轴自动缩放
    ShowGrid = true,
    ShowLegend = true,
    XAxisTitle = "时间",
    YAxisTitle = "数值"
};

// 添加数据点
curve.AddPoint(value);           // 追加到第一条序列
curve.AddPoint(0, value);        // 指定序列索引

// 多序列
curve.AddSeries("温度");
curve.AddSeries("压力");
curve.AddPoint(1, 65.5);
上下限报警
curve.UpperLimit = 90.0;   // 上限线
curve.LowerLimit = 10.0;   // 下限线
curve.LimitExceeded += (s, e) =>
{
    Console.WriteLine($"超限:{e.Value},方向:{e.Direction}");
};
绑定数据源
// 绑定 IEnumerable<HCurvePoint>
curve.DataSource = myDataList;
curve.XMember = "X";
curve.YMember = "Y";

HQrCoder - 二维码控件

基本二维码
var qr = new HQrCoder
{
    Location = new Point(10, 10),
    Size = new Size(200, 200),
    Text = "https://example.com",
    EccLevel = HQrEccLevel.M,    // 纠错等级:L/M/Q/H
    DarkColor = Color.Black,
    LightColor = Color.White
};
带 Logo 的二维码
var qrWithLogo = new HQrCoder
{
    Text = "扫码关注",
    EccLevel = HQrEccLevel.H,    // Logo 场景建议高纠错
    LogoImage = Properties.Resources.Logo,
    LogoSizeRatio = 0.2f,        // Logo 占比 20%
    LogoBackgroundEnabled = true,
    LogoBackgroundColor = Color.White
};

HFlowLayoutPanel - 流式布局面板

基本用法
var flowPanel = new HFlowLayoutPanel
{
    Dock = DockStyle.Top,
    AutoSize = true,
    FlowDirection = FlowDirection.LeftToRight,
    WrapContents = true,
    Radius = 8,
    Gradient = new Gradient<HFlowLayoutPanel>
    {
        Enabled = true,
        StartColor = Color.FromArgb(240, 240, 255),
        EndColor = Color.White
    }
};

消息通知系统

Toast 通知
// 信息通知(右上角自动消失)
HNotification.Notify("操作成功", "提示", MessageKind.Info);

// 警告 Toast
HWarningNotice.ShowToast("检测到异常温度", "温度警告");

// 错误 Toast
HErrorNotice.ShowToast("通讯超时", "错误");
报警对话框(需人工确认)
var result = HAlarm.Show("设备紧急停机,请检查!", "报警",
    new MessagePresentationOptions
    {
        ShowBackdrop = true,        // 显示模态遮罩
        AutoClose = false           // 禁止自动关闭
    });
模态警告/错误
HWarningNotice.ShowModal("参数超出范围", "警告");
HErrorNotice.ShowModal("数据库连接失败", "错误");
批量消息汇总
var messages = new[] { "报警1:温度过高", "报警2:压力超限", "报警3:流量异常" };
HMessageBatch.Show(messages, "报警汇总");
通过 MessagePresentationHub 统一调度
var presentResult = MessagePresentationHub.PresentModal(
    "确认执行此操作?",
    "操作确认",
    MessageBoxButtons.OKCancel,
    MessageBoxIcon.Question,
    owner: this,
    options: new MessagePresentationOptions { ShowBackdrop = true }
);
if (!presentResult.Successed)
    presentResult.Error(); // 可选
else if (presentResult.Content == DialogResult.OK)
{
    // 用户确认
}
自定义呈现请求
var result = MessagePresentationHub.Present(new MessageRequest
{
    Text = "批量报警消息",
    Caption = "报警汇总",
    Kind = MessageKind.Alarm,
    DisplayMode = MessageDisplayMode.Modal,
    MergeMode = MessageMergeMode.ScrollList,
    BatchItems = new[] { "报警A", "报警B", "报警C" },
    Owner = this,
    Options = new MessagePresentationOptions { ShowBackdrop = true }
});

VirtualKeyboard - 虚拟软键盘

基本用法
var keyboard = new VirtualKeyboard();
keyboard.Show(); // 显示软键盘

// 绑定目标输入框
keyboard.TargetTextBox = textBox1;

// 中文/英文切换
keyboard.IsChineseMode = true;
图片轮播
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
  • 显示类HLabelHTipsHPictureBoxHIconHLampHQrCoder
  • 输入类(含 PLC 地址)HTextBoxHComboBoxHCheckBoxHRadioButtonHTrackBarHDateTimePickerHMaskedTextBox
  • 数值调节HUpDown(替代标准 NumericUpDown,内部 HButton + HTextBox
  • 列表与链接(仅主题)HListBoxHListViewHLinkLabelHTreeView
  • 容器类HPanelHFlowLayoutPanelHUserControlHFormHGroupBoxHTabControlHSplitContainerHTableLayoutPanel
  • 菜单与条带(仅主题)HMenuStripHToolStripHStatusStripHContextMenuStrip
  • 特殊类HProgressBarHCircularProcessHLineHRollTextBoxCarouselHCurveHEditCheckBox
  • 通知类HNotificationHAlarmHErrorNoticeHWarningNoticeHMessageBatch

按功能查找

  • 地址管理Factory.AddressesFactory.ExtraAddressAddress
  • 事件系统EventHelper事件与委托
  • 主题系统ThemeManagerTheme主题系统
  • 主题持久化ThemePersistenceIniConfig主题持久化
  • 工厂模式Factory工厂与初始化系统
  • 设计时支持设计时支持集合与集合编辑器
  • 本地化系统LocalizationManagerFactory.InitializeLocalization本地化系统
  • 线程安全Invoked跨线程操作
  • 消息通知MessagePresentationHubHNotificationHAlarmPopupManager
  • Toast 堆叠ToastStackManagerToast 管理
  • 实时曲线HCurveHCurveDataBinder
  • 虚拟键盘VirtualKeyboardPinyinCandidatePopup
  • PLC 监控MelsoftConfigration

文档目录

核心特性

  • 30+ 工业控件:按钮、标签、文本框、面板、图片框等,均支持 PLC 地址绑定
  • 多状态外观:每个控件支持多状态外观配置,状态驱动 UI 切换
  • 18+ 主题系统:内置多种主题,支持一键切换全局样式
  • 设计时支持:完整的 Visual Studio 设计器支持,可视化编辑外观
  • PLC 通讯:统一的 IPlc 接口,支持 Modbus、串口、网络等多种通讯方式
  • 地址管理:自动收集、缓存、去重地址,支持动态范围与偏移
  • 界面重定向:支持窗体与用户控件的动态加载与切换
  • 字体图标:内置图标字体系统,支持矢量图标渲染
  • 事件总线:全局事件分发机制,解耦组件通信
  • 性能优化:LRU 缓存、批量更新、资源自动管理
  • 多语言支持:完整的本地化系统,支持 XML/RESX 多数据源,样式化本地化
  • 线程安全:提供跨线程安全操作工具,自动检测线程上下文,避免内存泄漏
  • 消息通知系统:Toast/模态/报警/批量消息统一调度,支持限流队列与堆叠管理
  • 实时曲线:基于 Chart 的高性能实时曲线控件,支持多序列、上下限报警、数据绑定
  • 二维码控件:原生无依赖 QR 码生成,支持 Logo 叠加与多纠错等级
  • 虚拟键盘:Win11 风格软键盘,支持中文拼音输入与候选词
  • 主题持久化:INI 文件持久化主题配置与 PLC 连接参数,自动迁移旧格式
  • Result 错误链:业务 API 统一 Result 返回,失败可经 InnerResult 追溯;库内不自动写日志,由消费方决定是否记录

组件功能说明(按文件)

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 句柄,并在数据包到达后更新;均返回 Result
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,实现 IPlcEntityIAuthorityFilterILockIContextITheme。支持单地址读写 SelectedIndex,并通过 Post/Send 在 UI 线程安全地更新数据源或选项。

参数/属性 作用
Address / NegationEnabled 绑定 PLC 地址,通讯刷新时更新 SelectedIndex,用户选择时写回。
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,支持跨线程更新。

Forms/HCurve.cs

基于 Chart 的高性能实时曲线控件,支持多序列、环形缓冲、上下限报警、数据绑定与缩放。

参数/属性 作用
Series (HCurveSeriesCollection) 曲线序列集合,每个序列可独立配置名称、颜色、线宽。
BufferCapacity 环形缓冲区容量(默认 1000),超出时自动滚动丢弃最早数据。
AutoIncrementX 是否自动递增 X 轴坐标(逐点追加模式)。
AutoScaleY 是否自动调整 Y 轴范围适应数据。
UpperLimit / LowerLimit 上下限标注线,超限时触发 LimitExceeded 事件。
ShowGrid / ShowLegend / ShowAxisLabels 控制网格、图例、坐标轴标签的显示。
ShowDataLabels 是否在数据点上显示标签。
ZoomEnabled / PanEnabled 启用鼠标缩放与平移。
RefreshThrottleMs 刷新节流间隔(毫秒),默认 16ms(约 60fps)。
XAxisTitle / YAxisTitle X/Y 轴标题。
YAxisMinimum / YAxisMaximum Y 轴手动范围(AutoScaleY = false 时生效)。
DataSource 绑定数据源(IEnumerable<HCurvePoint> 或多源 object[])。
XMember / YMember 数据绑定时的成员名(默认 XY)。
DataChanged 数据变化事件。
LimitExceeded 超限通知事件,参数含 Value 和方向。
ZoomChanged 缩放变化事件。
AddPoint(double value) 向第一条序列追加一个 Y 值。
AddPoint(int seriesIndex, double value) 向指定序列追加数据。
AddSeries(string name) 动态添加曲线序列。
ClearAll() 清空所有序列的数据。

Forms/HQrCoder.cs

原生无第三方依赖的二维码控件,支持 UTF-8 文本、多纠错等级、Logo 叠加。

参数/属性 作用
Text 二维码文本内容(UTF-8)。
EccLevel (HQrEccLevel) 纠错等级:L(7%)、M(15%)、Q(25%)、H(30%)。
QuietZoneModules 四周留白模块数(默认 4)。
DarkColor / LightColor 深色模块颜色与浅色背景颜色。
LogoImage 居中叠加 Logo 图片(建议配合 H 级纠错)。
LogoSizeRatio Logo 占二维码主体面积比例(默认 0.2f,建议 ≤ 0.3)。
LogoPaddingPixels Logo 四周填充像素数。
LogoBackgroundEnabled / LogoBackgroundColor Logo 背景填充,防止模块干扰。

Forms/HFlowLayoutPanel.cs

水平流式布局面板,继承 FlowLayoutPanel,额外支持圆角、渐变背景、主题、多状态外观。

参数/属性 作用
Radius 圆角半径,自动适配控件最小边。
Gradient 渐变背景配置。
Appearances (PanelAppearanceCollection) 多状态外观集合,状态驱动背景与颜色。
FilletStyle 圆角样式(四角/局部圆角)。
Post() / Send() 实现 IContext,支持跨线程更新子控件。

主题与事件

UIManagers/ThemeManager.cs

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

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

UIManagers/PopupManager.cs

弹窗全局治理,提供并发限制、连续打开检测、队列调度与事件通知。

成员 作用
MaxActivePopups 全局最大同时显示弹窗数(默认 10)。
ConsecutivePopupInterval 连续弹窗检测时间窗口(毫秒,默认 1000)。
MaxConsecutivePopups 时间窗口内允许的最大打开次数(默认 5)。
EnablePopupQueue 是否启用队列(被拒绝时入队)。
QueueProcessInterval 队列轮询间隔(毫秒,默认 500)。
ActivePopupCount 当前活跃弹窗数。
QueuedPopupCount 队列中等待的弹窗数。
PopupBlocked 弹窗被阻止时触发。
PopupQueued 弹窗进入队列时触发。
PopupDequeued 弹窗从队列取出并尝试显示时触发。
RequestShow(popup, ignoreLimits, useQueue, reason) 请求显示弹窗,返回 PopupShowResult(Shown/Queued/Blocked)。

UIManagers/MessagePresentationHub.cs

跨母版消息呈现调度中心,统一路由 Toast、模态、批量、队列等多种消息形态。

方法 作用
Present(MessageRequest request) 根据请求中的 DisplayMode/MergeMode 自动路由;返回 Result<DialogResult>
PresentModal(text, caption, buttons, icon, owner, options) 快捷显示模态消息框,返回 Result<DialogResult>
PresentToast(text, caption, kind, owner, options) 快捷显示 Toast 通知,返回 Result

UIManagers/ToastStackManager.cs

Toast 垂直堆叠管理,相同角落的 Toast 自动堆叠排列,最多显示 5 条,超出则关闭最早的。

方法 作用
Register(MessageBoxBase toast) 注册并堆叠 Toast,自动按位置模式分组。
TryMerge(PopupPositionMode mode, string message) 尝试将新消息合并追加到已有 Toast;返回 Result<bool>

特性

  • PopupPositionMode 分组管理(四个角落独立堆叠)
  • 关闭时自动重新排列剩余 Toast
  • 线程安全,支持跨线程调用 BeginInvokeIfRequired

UIManagers/ThemePersistence.cs

主题与类库配置持久化,在应用根目录 Ini/Hi.Ltd.ini 中保存并还原。

成员/方法 作用
YamlDir YAML 主题文件默认目录 <AppDir>/Yaml
IniPath INI 文件路径 <AppDir>/Ini/Hi.Ltd.ini
TryLoad() 从 INI 加载主题配置;返回 Result<ThemeStyle>,无配置时成功返回 Blue
Save(ThemeStyle style) 保存预置主题;返回 Result
SaveCustom(name, yamlPath) / SaveFont(ttf, yaml) 保存自定义主题/字体路径;返回 Result
TryLoadPlcConnection() 读取 PLC 连接参数;返回 Result<Connection>,未配置时成功返回默认值。
SavePlcConnection(...) 保存 PLC 连接参数;返回 Result
TryLoadFont() 读取自定义字体路径;返回 Result<(string ttf, string yaml)>
InitialThemeLoadResultThemeManager 静态构造时 TryLoad 的结果,失败时可查询完整错误链。
FontsDir 字体部署目录 <AppDir>/Fonts
DefaultMelsoftPort Melsoft 默认 TCP 端口(5562)。
DefaultPlcIpAddress 未配置时的默认 PLC IP(192.168.1.101)。

INI 文件结构Ini/Hi.Ltd.ini):

[Theme]
Style=Blue
UseCustom=false
CustomName=
CustomYamlPath=

[Font]
CustomTtfPath=
CustomYamlPath=

[Plc]
IpAddress=192.168.1.101
Port=5562

UIManagers/ModalBackdropForm.cs

模态遮罩窗体,在父窗体上方显示半透明遮罩,防止用户操作背景窗体。

方法 作用
ShowDialogWithBackdrop(owner, dialog) 显示带遮罩的模态对话框,对话框关闭后自动移除遮罩。

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 设置需要加载的程序集,自动扫描容器类型;内部调用 LoadAssemblyResult)。
Plc / InitializePlc(IPlc) 全局 PLC 通讯句柄;InitializePlc 返回 Result
LastRedirectionResult 重定向事件路径中最近一次失败结果(事件处理器无法直接返回 Result 时查询)。
addressCache LRU 缓存,按类型存储窗体/控件的地址集合,加速地址收集。
panelCache 按名称和索引缓存 Panel 控件,支持多界面共享同名画布。
addresses / ExtraAddress 当前活动地址列表与附加地址(需一直存在),支持线程安全访问。
GetInstance<T>(index, args) 获取或创建指定类型实例;返回 Result<T>
RemoveInstance<T>() 从缓存移除指定类型实例;返回 Result
AddOrUpdatePanel(Panel) 注册 Panel 到缓存;返回 Result
AddExtraAddress(Address) / RemoveExtraAddress(Address) / ClearExtraAddress() 管理附加地址;均返回 Result
LoadAssembly(Assembly) 加载程序集并建立类型映射;返回 Result
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) 地址序列化与反序列化;Deserialize 返回 Result<Address>
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 中说明,此处为几何命名空间下的数值范围工具。

消息与弹窗数据模型

Data/MessageRequest.cs

消息呈现请求 DTO,包含所有呈现所需参数,交由 MessagePresentationHub 路由。

属性 作用
Text 正文内容。
Caption 标题。
Kind (MessageKind) 严重级别(Info/Warning/Error/Alarm)。
DisplayMode (MessageDisplayMode) 展示形态(Auto/Modal/Toast)。
MergeMode (MessageMergeMode) 合并策略(Immediate/Queue/ScrollList)。
Buttons 模态按钮(MessageBoxButtons)。
Owner 所有者窗口。
BatchItems 批量消息项(与 ScrollList 模式配合)。
Options 呈现选项(MessagePresentationOptions)。

Data/MessagePresentationOptions.cs

消息呈现可选配置,覆盖弹窗预设中的默认值。

属性 作用
Preset (PopupPreset) 使用预设(Default/Toast/Alarm 等)。
PositionMode (PopupPositionMode) 弹窗位置(居中/四角)。
CustomPosition 自定义绝对坐标。
ShowAnimation / CloseAnimation (AnimationType) 显示/关闭动画。
AutoClose / AutoCloseDelayMs 是否自动关闭及延迟(毫秒)。
ShowBackdrop 是否显示模态遮罩。
MergeWindowMs 消息合并时间窗口(毫秒,默认 300)。
BodyLoadMode (MessageBodyLoadMode) 正文加载模式。

Data/MessageKind.cs

消息严重级别枚举:Info(信息)、Warning(警告)、Error(错误)、Alarm(工控报警)。

Data/MessageDisplayMode.cs

消息展示形态枚举:Auto(自动判断)、Modal(模态)、Toast(浮窗通知)。

Data/MessageMergeMode.cs

消息合并策略枚举:Immediate(立即显示)、Queue(队列排队)、ScrollList(批量滚动列表)。

Data/MessageBodyLoadMode.cs

消息正文加载模式枚举,控制正文的排版方式(单行/多行/滚动等)。

Data/PopupPositionMode.cs

弹窗位置模式枚举:ScreenCenter(屏幕居中)、ScreenTopRight(右上角)、ScreenTopLeft(左上角)、ScreenBottomRight(右下角)、ScreenBottomLeft(左下角)。

Data/PopupPreset.cs

弹窗预设枚举:Default(默认模态)、Toast(Toast 样式)、Alarm(报警样式,不可自动关闭)。

Data/AnimationType.cs

弹窗动画类型枚举,定义弹窗显示与关闭时的动画效果(淡入/淡出/滑入/滑出等)。

Data/HCurvePoint.cs

曲线数据点模型,包含 XY 坐标值,供 HCurve 数据绑定使用。

通讯接口与适配器

Interfaces/IPlc.cs

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

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

Interfaces/IPlcEntity.cs

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

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

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

上下调节控件,用于数值的增减操作。标准 WinForms NumericUpDown 的替代方案btn_Up/btn_DownHButton)配合 txb_ValueHTextBox,已支持 PLC 地址、主题与权限)。

Forms/Composition/LogManagement.cs

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

Forms/Composition/StatisticsControl.cs

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

Forms/Composition/HAlarm.cs

工控报警母版,需人工确认,不可自动关闭。

方法 作用
Show(text, caption, options) 显示报警对话框,阻塞直到用户确认。
Show(owner, text, caption, options) 带父窗口的报警对话框。
CreateAcknowledge() 创建报警确认实体(HAlarmAcknowledge)。

Forms/Composition/HErrorNotice.cs

错误通知母版,支持 Toast 浮窗与模态对话框两种形式。

方法 作用
ShowToast(text, caption, options) 显示 Toast 错误通知(非模态,自动消失)。
ShowToast(owner, text, caption, options) 带父窗口的 Toast 错误通知。
ShowModal(text, caption, options) 显示模态错误对话框(单确定)。
ShowModal(owner, text, caption, options) 带父窗口的模态错误对话框。

Forms/Composition/HWarningNotice.cs

警告通知母版,支持 Toast 浮窗与模态对话框两种形式。

方法 作用
ShowToast(text, caption, options) 显示 Toast 警告通知(非模态,自动消失)。
ShowModal(text, caption, options) 显示模态警告对话框(单确定)。

Forms/Composition/HNotification.cs

非模态通知母版,通过 ToastStackManager 自动堆叠显示。

方法 作用
Notify(text, caption, kind, options) 显示信息/警告/错误通知(MessageKind.Info/Warning/Error)。
Notify(owner, text, caption, kind, options) 带父窗口的通知。
CreateToast() 创建 Toast 通知实体。

Forms/Composition/HMessageBatch.cs

批量消息汇总母版,以滚动列表形式展示多条消息。

方法 作用
Show(items, caption, options) 显示滚动列表汇总对话框。
Show(owner, items, caption, options) 带父窗口的汇总对话框。

Forms/Composition/VirtualKeyboard.cs

Win11 风格软键盘,支持中文拼音输入与候选词,键位与输入框跟随主题。

特性 说明
中英文切换 IsChineseMode 属性控制中/英文输入模式。
拼音候选词 通过 PinyinCandidatePopup 独立弹窗显示候选词。
候选词配置 CandidateOptions 属性配置候选词弹窗外观。
主题跟随 继承 HForm,支持全局主题切换。
无边框拖动 内置标题栏(最小化/关闭按钮),支持拖动。
自适应布局 AdjustLayout() 随窗体大小缩放键位。

Forms/Composition/PinyinCandidatePopup.cs

拼音候选词弹窗,配合 VirtualKeyboard 使用,展示拼音候选汉字列表。

Forms/Composition/KeyboardInputHelper.cs

键盘输入辅助工具,提供软键盘与目标控件之间的输入路由。

Forms/Composition/ThemePreviewForm.cs

YAML 主题预览与微调窗体,展示 ThemeDefinition 解析后的色阶与按钮状态。

特性 说明
YAML 主题加载 从指定 YAML 文件路径加载主题定义。
色阶预览 以色块矩阵展示主题所有颜色。
按钮状态预览 展示不同状态下的按钮外观。
实时微调 支持运行时调整主题颜色并立即预览效果。

Forms/Composition/MelsoftConfigration.cs

三菱 MX Component(Melsoft)通讯测试与软元件实时监控窗体。

特性 说明
连接管理 连接/断开 PLC,与 Factory.Plc 全局同步。
软元件读写 支持 D、M、X、Y、SM 等软元件读写,位元件支持 ON/OFF/反转。
表格实时监控 以表格形式实时刷新软元件值,支持十进制/十六进制格式。
监控持久化 窗体打开时从本地恢复上次的地址配置,关闭时自动保存(Runtime/MelsecMonitor.json)。
地址规范 支持 D100M10X0Y10 等格式,非法行以粉底标注。
属性 作用
Plc PLC 通讯实例,可注入或继承 Factory.Plc

应用程序管理

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:应用程序设置

本地化系统

Localizations/LocalizationManager.cs

高性能本地化管理器(单例模式),提供多语言支持与样式化本地化能力。

成员 作用
Instance 单例实例,使用 Lazy<LocalizationManager> 模式。
CurrentCulture 当前文化信息。
CultureChanged 文化变更事件,参数为 CultureChangedEventArgs
GetString(string key, CultureInfo culture) 获取本地化字符串;返回 Result<string>
SwitchCulture(CultureInfo newCulture) 切换语言;返回 Result
UpdateResource(string key, string value, CultureInfo culture) 动态更新资源;返回 Result
RegisterSource(ILocalizationSource source, bool highPriority) 注册数据源;返回 Result
GetStyle(string key, CultureInfo culture) 获取指定 key 的样式(字体、颜色、位置等)。
GetGroupStyle(string groupName, CultureInfo culture) 获取样式组的样式。
GetControlStyle(string controlName, CultureInfo culture) 按控件名称获取样式。
RegisterSource(ILocalizationSource source, bool highPriority) 注册本地化数据源,支持优先级控制。

特性

  • LRU 缓存机制,提升资源查找性能
  • 编译委托缓存,将频繁访问的字符串转换为常量委托
  • 支持文化链回退(如 en-USen → 默认)
  • 批量更新定时器,避免频繁 UI 刷新
  • 多数据源支持(XML、RESX、DB 等),按优先级合并

Localizations/ILocalizationSource.cs

本地化数据源抽象接口,支持多种存储格式。

方法 作用
LoadAll(CultureInfo culture) 加载指定文化的所有字符串;返回 Result<IReadOnlyDictionary<string, string>>
TryGetString(string key, CultureInfo culture, out string value) 尝试获取指定 key 的本地化字符串。

Localizations/ResxLocalizationSource.cs

基于 RESX 文件的本地化数据源实现。

特性 说明
资源目录 默认从 Resources 目录加载 RESX 文件。
文件命名 支持 Resources.{culture}.resx 格式。
性能优化 内置缓存机制,避免重复加载。

Localizations/XmlLocalizationManager.cs

基于 XML 文件的本地化数据源实现,支持样式化本地化。

特性 说明
资源目录 默认从 Localization 目录加载 XML 文件。
样式支持 支持字体、颜色、位置、大小等样式配置。
控件样式 支持按控件名称配置样式。
分组样式 支持样式组,批量应用样式。

Localizations/LocalizationResxXmlConverter.cs

RESX 与 XML 格式之间的转换工具。

方法 作用
ConvertResxToXml(string resxPath, string xmlPath) 将 RESX 文件转换为 XML 格式。
ConvertXmlToResx(string xmlPath, string resxPath) 将 XML 文件转换为 RESX 格式。

Localizations/Models/Localized.cs

本地化数据模型定义。

作用
LocalizedString 本地化字符串模型,包含 Key、Value、Style、LastUpdated。
LocalizedControl 本地化控件模型,包含控件名称、类型、文本、工具提示、样式。
LocalizationStyle 本地化样式模型,支持字体、位置、大小、颜色、对齐、边距、可见性、启用状态等。

Localization.cs (Factory 扩展)

Factory 类添加本地化扩展方法,集成到工厂系统。

方法 作用
InitializeLocalization(string resourcesDirectory) 初始化本地化;返回 Result
ChangeCulture(string cultureName) 切换语言;返回 Result
GetLocalizedString(string key) 获取本地化字符串;返回 Result<string>
BindLocalization / SmartBindLocalization / AutoBindLocalization 绑定控件本地化;返回 Result
ApplyStyle / UpdateControlLocalization 应用或更新样式/文本;返回 Result
BindToolTipLocalization / BindLocalization(ToolStripItem) 绑定 ToolTip/菜单项;返回 Result

特性

  • 使用 ConditionalWeakTable 存储控件绑定信息,避免内存泄漏
  • 批量更新定时器,优化 UI 刷新性能
  • 支持样式化本地化,不仅翻译文本,还能调整控件外观
  • 自动提取本地化键(从 Tag 或 Name 属性)
  • 支持文化变更时自动更新所有绑定控件

LocalResourceConfig.cs

本地化资源配置类,用于存储 Hi.Ltd.LocalResource 所需的密钥和引擎信息。

属性 作用
ApiKey API 密钥(根据选择的引擎类型使用)。
SecretKey 密钥(根据选择的引擎类型使用)。
EngineType 翻译引擎类型(使用 object 存储枚举值,避免硬依赖)。
方法 作用
SyncToLocalResource() 将配置同步到 Hi.Ltd.LocalResource(如果可用)。
SyncFromLocalResource() 从 Hi.Ltd.LocalResource 同步配置(如果可用)。

特性

  • 插件方式设计,如果 Hi.Ltd.LocalResource 类库不存在则仅存储配置
  • 使用反射动态加载和访问 Hi.Ltd.LocalResource
  • 线程安全的配置更新
  • 自动检测类库可用性

跨线程操作

Threading/Invoked.cs

WinForm 跨线程控件操作工具类,提供线程安全的控件更新方法。

方法 作用
Add<T1, T2>(this T1 ctrl, IEnumerable<T2> items, DockStyle dockStyle, SynchronizationContext context) 跨线程添加多个子控件到父控件。
UpdateAction<T>(this Control control, Action<object[]> action, SynchronizationContext context, params object[] args) 跨线程执行控件操作。
Remove<T>(this Control control, T child, SynchronizationContext context) 跨线程移除子控件。
Clear<T>(this Control control, SynchronizationContext context) 跨线程清空子控件。

特性

  • 自动检测线程上下文,无需手动判断 InvokeRequired
  • 使用 WeakReference 避免内存泄漏和访问已释放的控件
  • 双重状态检查,确保控件在执行时仍然有效
  • 支持 SynchronizationContextControl.Invoke 两种方式
  • 异常安全处理,避免因控件释放导致的崩溃
  • 批量操作优化(使用 AddRangeSuspendLayout/ResumeLayout

使用示例

// 从后台线程更新控件文本
this.textBox1.UpdateAction(args => 
{
    if (args?.Length > 0)
        this.textBox1.Text = args[0].ToString();
}, null, "新文本");

// 批量添加子控件
this.panel1.Add(new[] { button1, button2, button3 }, DockStyle.Top);

其它模块说明

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

使用建议

初始化流程

  1. Factory.LoadAssembly(assembly) 或设置 Factory.Assembly(返回/传播 Result)。
  2. Factory.InitializePlc(IPlc) 注入通讯句柄,检查 Successed
  3. Factory.InitializeComponent() 初始化窗体并收集地址。
  4. 启动 PLC 通讯线程,定期 ReadDeviceRandom 并触发 EventHelper.OnValueChanged

主题切换

var updateResult = ThemeManager.Update(ThemeStyle.Blue);
if (!updateResult.Successed)
    updateResult.Error(); // 可选

主题持久化

var loadResult = ThemePersistence.TryLoad();
if (loadResult.Successed)
    ThemeManager.Update(loadResult.Content);
else
    loadResult.Error(); // 可选;或 Recover 回退 Blue

界面重定向

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

地址管理

var address = new Address { SoftType = SoftType.D, Index = 100, DataType = DataType.UInt16 };
var addResult = Factory.AddExtraAddress(address);
if (!addResult.Successed)
    return Error.Result(nameof(Factory.AddExtraAddress), addResult);

控件外观配置

在设计器中编辑 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);
    
    // 设置程序集
    var loadResult = Factory.LoadAssembly(Assembly.GetExecutingAssembly());
    if (!loadResult.Successed)
    {
        loadResult.Error(); // 可选
        return;
    }
    
    // 初始化 PLC 通讯
    var plc = new ModbusDevice();
    plc.IpAddress = "192.168.1.100";
    plc.Port = 502;
    var openResult = plc.Open();
    if (!openResult.Successed)
    {
        openResult.Error(); // 可选
        return;
    }
    var initPlcResult = Factory.InitializePlc(plc);
    if (!initPlcResult.Successed)
        return;
    
    // 初始化窗体
    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)
            {
                var readResult = Factory.Plc.ReadDeviceRandom(addresses, out var values);
                if (readResult.Successed)
                    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);
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}");

版本历史

主要版本特性

  • 2026.6.30+(本地构建,尚未上传 NuGet):对外业务 API 统一 Result 返回,错误链经 InnerResult 追溯;类库内不自动写日志。未升级的旧版包不受影响。
  • v1.0+: 基础控件库,支持 PLC 通讯、多状态外观、主题系统
  • 支持 30+ 工业控件
  • 18+ 内置主题
  • 完整的设计时支持
  • Modbus/串口/网络通讯适配器

许可证

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

API 快速参考

核心静态类

Factory(工厂类)
// 程序集管理
var loadResult = Factory.LoadAssembly(Assembly.GetExecutingAssembly());
if (!loadResult.Successed) return loadResult;
// 或设置 Factory.Assembly(内部调用 LoadAssembly)

// PLC 通讯
Factory.Plc = plc;
var initResult = Factory.InitializePlc(plc);
if (!initResult.Successed) return initResult;

// 实例管理
// 与旧版等价(显式类型触发隐式转换)
MainForm form = Factory.GetInstance<MainForm>();
Application.Run(form);

// 或显式检查错误链
var formResult = Factory.GetInstance<MainForm>();
if (!formResult.Successed) return Error.Result(nameof(Factory.GetInstance), formResult);
Application.Run(formResult.Content);

MainForm form2 = Factory.GetInstance<MainForm>(index: 1);
Factory.RemoveInstance<MainForm>();

// 地址管理
Factory.Addresses;
Factory.ExtraAddress;
Factory.AddExtraAddress(address);
Factory.RemoveExtraAddress(address);

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

// 重定向失败查询
if (!Factory.LastRedirectionResult.Successed)
    Factory.LastRedirectionResult.Error();

// 初始化
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(主题管理)
// 切换主题
var updateResult = ThemeManager.Update(ThemeStyle.Blue);
if (!updateResult.Successed)
    updateResult.Error(); // 可选

// 静态构造时主题加载结果(失败时可查链)
if (!ThemeManager.InitialThemeLoadResult.Successed)
    ThemeManager.InitialThemeLoadResult.Error();

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

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

// 获取可用主题
var themes = ThemeManager.GetAvailableThemeStyles();
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(); // 序列化为字符串
var addrResult = Address.Deserialize(str); // Result<Address>
if (!addrResult.Successed) return addrResult;
var addr = addrResult.Content;
集合扩展
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. 错误处理(Result)

// ✅ 推荐:检查 Successed,由应用决定是否记录
var result = Factory.InitializePlc(plc);
if (!result.Successed)
{
    result.Error(); // 可选
    return;
}

// ✅ 推荐:包装上游失败,保留 InnerResult
var loadResult = ThemePersistence.TryLoad();
if (!loadResult.Successed)
    return Error.Result(nameof(ThemePersistence.TryLoad), loadResult);

// ❌ 不推荐:只取 Message 丢链
// if (!r.Successed) Log(r.Message);

代码示例集合

示例 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
        };
        
        var openResult = plc.Open();
        if (!openResult.Successed)
        {
            openResult.Error(); // 可选
            return;
        }
        var initResult = Factory.InitializePlc(plc);
        if (!initResult.Successed)
            return;
        StartCommunicationThread();
    }

    private void StartCommunicationThread()
    {
        Task.Run(() =>
        {
            while (Factory.Plc?.Connected == true)
            {
                try
                {
                    var addresses = Factory.Addresses?.ToList();
                    if (addresses?.Count > 0)
                    {
                        var readResult = Factory.Plc.ReadDeviceRandom(addresses, out var values);
                        if (readResult.Successed)
                        {
                            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"

// 反序列化字符串为地址
var deserializeResult = Address.Deserialize(serialized);
if (deserializeResult.Successed)
{
    var deserialized = deserializeResult.Content;
}

渐变配置详解

基本渐变
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              // 重试次数
};

// 打开连接
var openResult = modbus.Open();
if (openResult.Successed)
{
    var initResult = Factory.InitializePlc(modbus);
    if (initResult.Successed)
        EventHelper.OnMessageChanged?.Invoke("PLC 连接成功", Color.Green);
    else
        initResult.Error(); // 可选
}
else
{
    openResult.Error(); // 可选
}
串口通讯配置
var serialPort = new SerialPortAdapter
{
    PortName = "COM3",
    BaudRate = 9600,
    DataBits = 8,
    Parity = Parity.None,
    StopBits = StopBits.One,
    SlaveAddress = 1
};

// 打开连接
var openResult = serialPort.Open();
if (openResult.Successed)
    Factory.InitializePlc(serialPort);
批量读取地址
// 获取所有需要读取的地址
var addresses = Factory.Addresses?.ToList();
    if (addresses?.Count > 0)
    {
        var readResult = Factory.Plc.ReadDeviceRandom(addresses, out var values);
        if (readResult.Successed)
            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 }
};

// 随机写入
var writeResult = Factory.Plc.WriteDeviceRandom(addresses);
if (writeResult.Successed)
    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>();

// 获取窗体实例(自动创建或从缓存获取)
MainForm form = Factory.GetInstance<MainForm>();
Application.Run(form);

// 或显式检查:var formResult = ...; if (!formResult.Successed) return formResult;

// 移除实例
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.7.11.1653 41 7/11/2026
2026.7.7.1823 89 7/7/2026
2026.6.29.1817 107 6/29/2026
2026.6.12.959 132 6/12/2026 2026.6.12.959 is deprecated because it has critical bugs.
2026.6.2.859 115 6/8/2026
2026.5.29.905 119 5/29/2026
2026.4.15.1112 124 4/15/2026
2026.4.13.1111 117 4/13/2026
2026.4.9.1135 108 4/13/2026
2026.3.17.1737 118 3/27/2026
2025.5.7.1007 211 5/7/2025
2025.4.29.1133 222 4/29/2025
2025.2.18.1652 165 2/26/2025

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