# 如何集成到你的 C# 项目中

## 1. 添加 LicenseHelper.cs 到你的项目

1. 在你的解决方案里新建一个文件夹 `LicenseLib/`
2. 把 `LicenseHelper.cs` 放进去
3. 在 Visual Studio 中右键项目 → 添加现有项 → 选择 LicenseHelper.cs
4. 安装 NuGet 包（右键项目 → 管理 NuGet 包）：
   ```
   System.Management
   ```

## 2. 修改私钥（必须！）

打开 `LicenseHelper.cs`，找到这行：

```csharp
private static readonly byte[] _privateKeyEncrypted = { 0x4D, 0x79, 0x53, 0x65, 0x63, ... };
```

**把它改成你自己的密钥。** 方法：

```csharp
// 1. 先写一个你的暗码，比如 "MySecretKey123!@#"
// 2. 用这个工具函数加密：
static byte[] EncryptKey(string plainKey)
{
    byte[] result = new byte[plainKey.Length];
    for (int i = 0; i < plainKey.Length; i++)
        result[i] = (byte)(plainKey[i] ^ 0x2A);  // 0x2A 是异或密钥，也可以改
    return result;
}
// 3. 把输出的 byte 数组替换到 _privateKeyEncrypted
```

> ⚠️ **不同人用不同私钥**，不然别人拿到你的工具也能生成合法序列号！

## 3. 应用完整性校验（可选但推荐）

编译 Release 后，运行一次得到自身 MD5：

```csharp
// 在 Main 入口加一行
string md5 = LicenseHelper.GetSelfMd5();
// 输出结果，复制到 CheckIntegrity() 里的 expectedHash
```

然后取消 `CheckIntegrity()` 里的注释。这样 exe 被修改后会自动退出。

## 4. 在你的主窗口加注册逻辑

### 启动时（Program.cs 或 MainForm_Load）

```csharp
// 防多开
LicenseHelper.CheckSingleInstance();

// 防调试
LicenseHelper.CheckDebugger();

// 检查是否已授权
if (!LicenseHelper.IsLicensed())
{
    // 弹出注册窗口
    RegForm regForm = new RegForm();
    if (regForm.ShowDialog() != DialogResult.OK)
    {
        Application.Exit();
        return;
    }
}
```

### 注册窗口的确认按钮

```csharp
private void btnOK_Click(object sender, EventArgs e)
{
    string inputCode = txtRegCode.Text.Trim();
    string machineCode = LicenseHelper.GetLocalMachineCode();

    if (LicenseHelper.CheckRegister(inputCode, machineCode))
    {
        LicenseHelper.SaveLicensedFlag();
        MessageBox.Show("注册成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
        DialogResult = DialogResult.OK;
        Close();
    }
    else
    {
        // 每次失败后随机延迟 1-3 秒，防止暴力破解
        System.Threading.Thread.Sleep(new Random().Next(1000, 3000));
        MessageBox.Show("注册码无效，请检查后重试", "注册失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
    }
}
```

## 5. 发布前加固打包流程

```
源码编写 → 编译 Release → ConfuserEx 混淆 → 
[可选] VMProtect 虚拟化 → [可选] 签名 → 发布
```

### ConfuserEx 配置
见 `ConfuserEx配置说明.md`

### VMProtect（商业级）
- 购买地址：https://vmpsoft.com
- 只保护核心函数：`CheckRegister`、`GetPrivateKey`
- 开启：Virtualization + Mutation + Anti-Debug + Anti-Dump

## 6. 使用流程

```
① 用户打开软件 → 显示机器码 → 复制发给你
② 你运行 LicenseGen.exe → 输入机器码 → 得到注册码 → 发给用户
③ 用户输入注册码 → 本地校验通过 → 解锁全部功能
                          全程离线，无需联网
```
