现象:网页点「启动本机软件」/双击 exe 弹「You must install .NET Desktop Runtime」, 网页表现为唤起没反应、查询失败。 根因有两个: 1. 协议注册表指向的是 bin\Debug 的 framework-dependent exe,它靠 DOTNET_ROOT 找运行时; 而浏览器/资源管理器/协议拉起的进程拿不到我们临时设的环境变量 → 直接弹安装提示。 更糟的是协议只在主窗口手动点按钮才注册,换目录/换构建后注册表一直是旧路径。 2. 单实例的命名管道监听是在「登录完成、主窗口出现」之后才 StartListening, 用户卡在登录窗期间被协议唤起 → 参数无人接收(第二个实例连不上管道就直接退出了)。 修复: - App.EnsureProtocolRegistered():每次启动把 HKCU 的 command 校正到 Environment.ProcessPath, 与当前 exe 一致时跳过(幂等);不一致时重注册并记日志(含原路径,方便排查)。 - _single.StartListening() 提前到启动服务之后、登录之前。 - 登录期间收到唤起:存 pending code 并把登录窗叫到前面,登录完成后自动查询(原有逻辑保留)。 - 抽出 BringLoginWindowToFront(),OnLoginRequested / 第二次双击(不带 URL)也走它—— 以前登录期间再双击 exe 是彻底没反应的。 - MainWindow 的协议状态改为显示「是否指向当前 exe」,指向旧路径时提示重启会自动校正。 分发形态改为自包含: - desktop/nuget.config 指向华为云 NuGet 镜像(本机访问不了 api.nuget.org), 自包含发布要下载 Microsoft.*.App.Runtime.win-x64; - dotnet publish -c Release -r win-x64 --self-contained true -p:PublishSingleFile=true -p:IncludeNativeLibrariesForSelfExtract=true -o publish → 单文件约 154 MB,双击/协议唤起都能直接跑。 - publish/ 已在 .gitignore 里。 实测(全程清掉 DOTNET_ROOT,模拟用户环境): - 冷启动:yuncang://open?code=COLD123 → 进程起来 → 恢复登录 → 自动查询 COLD123; - 已运行时:yuncang://open?code=TEST999 → 管道转发到原实例 → 主窗口前置并查询; - 注册表自动从 bin\Debug 校正到 publish\...exe(日志有记录); - 网页 /local?code=ABC123 → 已登录 → 正常展示查询结果(真实桌面端,非 mock)。
261 lines
8.1 KiB
C#
261 lines
8.1 KiB
C#
using System;
|
||
using System.Collections.ObjectModel;
|
||
using System.ComponentModel;
|
||
using System.Diagnostics;
|
||
using System.Windows;
|
||
using System.Windows.Input;
|
||
using System.Windows.Media;
|
||
using YuncangTrace.LocalService.Services;
|
||
|
||
namespace YuncangTrace.LocalService;
|
||
|
||
/// <summary>
|
||
/// 主窗口:本机服务状态、启动协议、测试查询、日志、当前登录用户
|
||
///
|
||
/// 关窗口**不是退出**:只是隐藏到托盘(本机服务得继续跑)。
|
||
/// 真正退出:托盘菜单「退出」,或点「退出登录」后再取消登录。
|
||
/// </summary>
|
||
public partial class MainWindow : Window
|
||
{
|
||
private readonly ObservableCollection<string> _logs = new();
|
||
private readonly LocalHttpServer _server;
|
||
private readonly OrderQueryService _queryService = new();
|
||
|
||
/// <summary>允许真正关闭窗口(退出登录 / 退出程序时由 App 置 true)</summary>
|
||
public bool AllowClose { get; set; }
|
||
|
||
/// <summary>用户点了「退出登录」</summary>
|
||
public event Action? LogoutRequested;
|
||
|
||
/// <summary>窗口被隐藏到托盘(用来弹一次气泡提示)</summary>
|
||
public event Action? HiddenToTray;
|
||
|
||
/// <summary>本机服务的启/停状态变了(App 用它同步托盘上的文案)</summary>
|
||
public event Action? ServiceStateChanged;
|
||
|
||
public MainWindow(LocalHttpServer server, AppSettings settings, Session session)
|
||
{
|
||
InitializeComponent();
|
||
|
||
_server = server;
|
||
|
||
UserText.Text = $"已登录:{session.DisplayName}";
|
||
UserText.ToolTip = $"服务器:{settings.ServerBaseUrl}";
|
||
AddressBox.Text = _server.BaseUrl;
|
||
|
||
// 日志:先灌历史(服务在登录前就起来了),再订阅新的
|
||
foreach (var line in AppLog.History) _logs.Add(line);
|
||
|
||
LogList.ItemsSource = _logs;
|
||
AppLog.Written += OnLogWritten;
|
||
|
||
Loaded += (_, _) =>
|
||
{
|
||
UpdateServerState();
|
||
UpdateProtocolState();
|
||
};
|
||
Closing += OnClosing;
|
||
Closed += (_, _) => AppLog.Written -= OnLogWritten;
|
||
}
|
||
|
||
/// <summary>
|
||
/// 被协议拉起 / 另一个实例把参数转过来时调用:<c>yuncang://open?code=xxx</c>
|
||
/// </summary>
|
||
public void HandleLaunchUrl(string url)
|
||
{
|
||
AppLog.Write($"收到启动协议:{url}");
|
||
|
||
var code = ProtocolHelper.ParseCode(url);
|
||
if (code is null)
|
||
{
|
||
AppLog.Write("协议里没带 code,忽略");
|
||
return;
|
||
}
|
||
|
||
QueryBox.Text = code;
|
||
RunQuery();
|
||
}
|
||
|
||
// ---------------- 服务启停 ----------------
|
||
|
||
private void StartStop_Click(object sender, RoutedEventArgs e)
|
||
{
|
||
if (_server.IsRunning)
|
||
{
|
||
_server.Stop();
|
||
}
|
||
else
|
||
{
|
||
try
|
||
{
|
||
_server.Start();
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
AppLog.Write($"启动本机服务失败:{ex.Message}");
|
||
MessageBox.Show(this, ex.Message, "启动失败", MessageBoxButton.OK, MessageBoxImage.Warning);
|
||
}
|
||
}
|
||
|
||
UpdateServerState();
|
||
}
|
||
|
||
private void UpdateServerState()
|
||
{
|
||
var running = _server.IsRunning;
|
||
|
||
StatusText.Text = running ? $"运行中 · {_server.BaseUrl}" : "未启动";
|
||
StatusDot.Fill = (Brush)FindResource(running ? "OkBrush" : "BadBrush");
|
||
StartStopButton.Content = running ? "停止服务" : "启动服务";
|
||
|
||
ServiceStateChanged?.Invoke();
|
||
}
|
||
|
||
// ---------------- 启动协议 ----------------
|
||
|
||
private void Protocol_Click(object sender, RoutedEventArgs e)
|
||
{
|
||
try
|
||
{
|
||
if (ProtocolHelper.IsRegistered())
|
||
{
|
||
var answer = MessageBox.Show(this,
|
||
"已注册启动协议。要取消注册吗?(取消后网页就无法叫醒本软件)",
|
||
"启动协议", MessageBoxButton.YesNo, MessageBoxImage.Question);
|
||
if (answer != MessageBoxResult.Yes) return;
|
||
|
||
ProtocolHelper.Unregister();
|
||
AppLog.Write("已取消注册启动协议");
|
||
}
|
||
else
|
||
{
|
||
ProtocolHelper.Register();
|
||
AppLog.Write($"已注册启动协议:{ProtocolHelper.Scheme}:// → {ProtocolHelper.RegisteredCommand()}");
|
||
}
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
AppLog.Write($"操作启动协议失败:{ex.Message}");
|
||
MessageBox.Show(this, ex.Message, "启动协议", MessageBoxButton.OK, MessageBoxImage.Warning);
|
||
}
|
||
|
||
UpdateProtocolState();
|
||
}
|
||
|
||
private void UpdateProtocolState()
|
||
{
|
||
var registered = ProtocolHelper.IsRegistered();
|
||
var command = ProtocolHelper.RegisteredCommand();
|
||
var exe = Environment.ProcessPath;
|
||
|
||
// 注册表指向的必须就是当前这个 exe(否则网页叫醒拿到的是旧路径/开发目录里的 exe)
|
||
var pointsToMe = command is not null && exe is not null
|
||
&& command.IndexOf(exe, StringComparison.OrdinalIgnoreCase) >= 0;
|
||
|
||
ProtocolButton.Content = registered ? "取消启动协议" : "注册启动协议";
|
||
ProtocolText.Text = !registered
|
||
? $"未注册 {ProtocolHelper.Scheme}://(网页无法叫醒本软件)"
|
||
: pointsToMe
|
||
? $"已注册 {ProtocolHelper.Scheme}://(网页可叫醒本软件)"
|
||
: $"已注册,但指向旧路径(重启本软件会自动校正)";
|
||
}
|
||
|
||
// ---------------- 查询 ----------------
|
||
|
||
private void Query_Click(object sender, RoutedEventArgs e) => RunQuery();
|
||
|
||
private void QueryBox_KeyDown(object sender, KeyEventArgs e)
|
||
{
|
||
if (e.Key == Key.Enter) RunQuery();
|
||
}
|
||
|
||
private void RunQuery()
|
||
{
|
||
var code = QueryBox.Text.Trim();
|
||
AppLog.Write($"查询:{code}");
|
||
|
||
var result = _queryService.Query(code);
|
||
ResultBox.Text = result.Ok
|
||
? JsonUtil.ToPrettyJson(result.Data)
|
||
: $"{(int)result.StatusCode} {result.Message}";
|
||
|
||
ResultBox.ScrollToHome();
|
||
}
|
||
|
||
// ---------------- 退出登录 / 关闭 ----------------
|
||
|
||
private void Logout_Click(object sender, RoutedEventArgs e)
|
||
{
|
||
var answer = MessageBox.Show(this,
|
||
$"要退出登录吗?(本机服务会继续运行,重新登录后可继续使用)",
|
||
"退出登录", MessageBoxButton.YesNo, MessageBoxImage.Question);
|
||
if (answer != MessageBoxResult.Yes) return;
|
||
|
||
LogoutRequested?.Invoke();
|
||
}
|
||
|
||
private void OnClosing(object? sender, CancelEventArgs e)
|
||
{
|
||
if (AllowClose) return;
|
||
|
||
// 关窗口 = 缩到托盘,别把本机服务带走
|
||
e.Cancel = true;
|
||
Hide();
|
||
HiddenToTray?.Invoke();
|
||
}
|
||
|
||
// ---------------- 小工具 ----------------
|
||
|
||
private void CopyAddress_Click(object sender, RoutedEventArgs e) => CopyText(_server.BaseUrl);
|
||
|
||
private void CopyLaunchUrl_Click(object sender, RoutedEventArgs e)
|
||
=> CopyText(ProtocolHelper.LaunchUrl(QueryBox.Text.Trim()));
|
||
|
||
private void OpenInBrowser_Click(object sender, RoutedEventArgs e)
|
||
{
|
||
try
|
||
{
|
||
Process.Start(new ProcessStartInfo($"{_server.BaseUrl}/api/health") { UseShellExecute = true });
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
AppLog.Write($"打开浏览器失败:{ex.Message}");
|
||
}
|
||
}
|
||
|
||
private void CopyText(string text)
|
||
{
|
||
try
|
||
{
|
||
Clipboard.SetText(text);
|
||
AppLog.Write($"已复制:{text}");
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
AppLog.Write($"复制失败:{ex.Message}");
|
||
}
|
||
}
|
||
|
||
/// <summary>日志(HTTP 服务线程也会触发,切回 UI 线程再改集合)</summary>
|
||
private void OnLogWritten(string line)
|
||
{
|
||
if (!Dispatcher.CheckAccess())
|
||
{
|
||
Dispatcher.BeginInvoke(new Action(() => Append(line)));
|
||
return;
|
||
}
|
||
|
||
Append(line);
|
||
}
|
||
|
||
private void Append(string line)
|
||
{
|
||
_logs.Add(line);
|
||
|
||
// 只留最近 300 行
|
||
while (_logs.Count > 300) _logs.RemoveAt(0);
|
||
|
||
if (_logs.Count > 0) LogList.ScrollIntoView(_logs[^1]);
|
||
}
|
||
}
|