packServer/desktop/Services/SingleInstance.cs
liufumingren 51abccbaaf desktop:加登录页、托盘图标、防多开(单实例 + 参数转发)
- LoginWindow:服务器地址 / 账号 / 密码 / 记住账号 → POST /api/web/auth/login 拿 user JWT;
  本地已有令牌时先用 GET /api/web/me 验证,有效就跳过登录(窗口一闪而过),无效清掉令牌留下重登。
- TrayIconService(WinForms NotifyIcon,csproj 开 UseWindowsForms):
  关窗口 = 隐藏到托盘(本机服务继续跑),双击托盘恢复,右键菜单「打开主界面 / 服务地址 / 版本 / 退出」;
  第一次缩到托盘冒一次气泡提示。退出只走托盘「退出」(App 改 ShutdownMode=OnExplicitShutdown)。
- 防多开:SingleInstance(Local\ 命名互斥体 + 命名管道)。第二个实例不抢 17311 端口,
  把 yuncang://open?code=… 转给已运行实例(在托盘里也会被弹出来并按 code 查询)后自己退出;
  还在登录界面时先把 URL 存起来,登录完成后再查。
- 生命周期调整:本机 HTTP 服务与托盘在 App 里创建(登录前就可用),主窗口只管展示与操作;
  日志改成全局 AppLog(窗口没开时的日志也会在窗口打开后补上)。
- 新增 AppSettings / SessionStore:%LOCALAPPDATA%\YuncangTrace\settings.json、session.json
  (服务器地址默认 http://127.0.0.1:7300;换服务器不会复用旧令牌)。
- 新增 ApiClient(登录 / 校验令牌)、MainWindow「退出登录」(清令牌回登录页)。
- 程序/托盘图标:Assets/app.ico + tools/make-icon.ps1(品牌蓝 + 白色播放三角)。
- csproj 关闭 ImplicitUsings:WPF 与 WinForms 同时开启时隐式命名空间会让
  MessageBox / Application / Clipboard 等产生歧义。

⚠️ 本机没有 .NET SDK,无法编译验证;已做 XAML/XML 良构与括号平衡检查。
2026-10-17 10:23:50 +08:00

121 lines
3.8 KiB
C#

using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Pipes;
using System.Text;
using System.Threading;
namespace YuncangTrace.LocalService.Services;
/// <summary>
/// 单实例 + 参数转发(命名管道)
///
/// 场景:窗口已经开着,用户又点了一次 WMS 页面上的「查看打包视频」→ 系统按协议再启动一次本程序。
/// 这时第二个实例**不应该**去抢 17311 端口,而是把 `yuncang://open?code=xxx` 通过管道送给第一个实例,
/// 由它把窗口激活并查询那个运单号。
/// </summary>
public sealed class SingleInstance : IDisposable
{
private readonly Mutex _mutex;
private readonly string _pipeName;
private readonly Action<string[]> _onArgs;
private readonly CancellationTokenSource _cts = new();
private readonly bool _ownsMutex;
/// <summary>本次是否是第一个实例(不是的话调用 <see cref="SendArgs"/> 后就可以退出了)</summary>
public bool IsFirstInstance { get; }
public SingleInstance(string name, Action<string[]> onArgs)
{
_onArgs = onArgs;
_pipeName = $"{name}.pipe";
// 全局命名互斥体:跨会话也能认出来(同一个用户下就够了,用 Local\ 前缀)
_mutex = new Mutex(initiallyOwned: true, $@"Local\{name}.mutex", out var createdNew);
_ownsMutex = createdNew;
IsFirstInstance = createdNew;
}
/// <summary>第一个实例调用:开一个后台线程等第二个实例送参数过来</summary>
public void StartListening()
{
var thread = new Thread(ListenLoop)
{
IsBackground = true,
Name = "single-instance-pipe",
};
thread.Start();
}
/// <summary>第二个实例调用:把命令行参数送给已运行的实例(连不上就算了,不影响退出)</summary>
public void SendArgs(string[] args)
{
if (args.Length == 0) return;
try
{
using var client = new NamedPipeClientStream(".", _pipeName, PipeDirection.Out);
client.Connect(1500);
using var writer = new StreamWriter(client, new UTF8Encoding(false)) { AutoFlush = true };
foreach (var arg in args) writer.WriteLine(arg);
}
catch (Exception)
{
// 拿不到第一个实例(可能正在退出):静默忽略,用户重新点一次即可
}
}
private void ListenLoop()
{
while (!_cts.IsCancellationRequested)
{
try
{
using var server = new NamedPipeServerStream(
_pipeName, PipeDirection.In, NamedPipeServerStream.MaxAllowedServerInstances,
PipeTransmissionMode.Byte, PipeOptions.None);
server.WaitForConnection();
var args = new List<string>();
using (var reader = new StreamReader(server, new UTF8Encoding(false)))
{
string? line;
while ((line = reader.ReadLine()) is not null)
{
if (line.Length > 0) args.Add(line);
}
}
if (args.Count > 0) _onArgs(args.ToArray());
}
catch (Exception)
{
if (_cts.IsCancellationRequested) return;
Thread.Sleep(200);
}
}
}
public void Dispose()
{
_cts.Cancel();
if (_ownsMutex)
{
try
{
_mutex.ReleaseMutex();
}
catch (ApplicationException)
{
// 不持有互斥体(理论上不会发生)
}
}
_mutex.Dispose();
_cts.Dispose();
}
}