-
Notifications
You must be signed in to change notification settings - Fork 183
Expand file tree
/
Copy pathMainForm_Transparent.cs
More file actions
365 lines (315 loc) · 13.4 KB
/
MainForm_Transparent.cs
File metadata and controls
365 lines (315 loc) · 13.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
using LiteMonitor.src.Core;
using LiteMonitor.src.SystemServices;
using LiteMonitor.src.UI;
using LiteMonitor.src.UI.Helpers;
using System;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace LiteMonitor
{
public class MainForm : Form
{
private readonly Settings _cfg = Settings.Load();
private UIController? _ui;
// ★★★ 双助手架构 ★★★
private readonly MainFormWinHelper _winHelper;
private readonly MainFormBizHelper _bizHelper;
private readonly int _wmTaskbarCreated;
private const int WM_DISPLAYCHANGE = 0x007E;
private CancellationTokenSource _displayChangeCts;
private Point _dragOffset;
private bool _uiDragging = false;
private System.Windows.Forms.Timer? _topMostGuardTimer;
// 防止 Win11 自动隐藏无边框 + 无任务栏窗口
protected override CreateParams CreateParams
{
get
{
var cp = base.CreateParams;
cp.ExStyle |= 0x80; // WS_EX_TOOLWINDOW
cp.ExStyle &= ~0x00040000; // WS_EX_APPWINDOW
// [Fix] 启动时应用鼠标穿透配置,防止因句柄重建导致样式丢失
if (_cfg != null && _cfg.ClickThrough)
{
cp.ExStyle |= 0x20; // WS_EX_TRANSPARENT
cp.ExStyle |= 0x80000; // WS_EX_LAYERED (必须配合才能实现完整穿透)
}
return cp;
}
}
// ========== 代理方法 (保持兼容性) ==========
public void SetClickThrough(bool enable) => _winHelper.SetClickThrough(enable);
public void InitAutoHideTimer() => _bizHelper.StartTimer();
public void StopAutoHideTimer() => _bizHelper.StopTimer();
public void HideTrayIcon() => _bizHelper.SetTrayVisible(false);
public void ShowTrayIcon() => _bizHelper.SetTrayVisible(true);
public void RebuildMenus() => _bizHelper.RebuildMenus();
public void ShowNotification(string title, string text, ToolTipIcon icon) => _bizHelper.ShowNotification(title, text, icon);
// 供 Helper 调用
public void ToggleLayoutMode() => _bizHelper.ToggleLayoutMode();
public void EnsureVisibleAndSavePos() => _bizHelper.SavePos();
public void ApplyRoundedCorners() => _winHelper.ApplyRoundedCorners();
// 供外部调用
public void OpenTaskManager() => _bizHelper.OpenTaskManager();
public void OpenSettings() => _bizHelper.OpenSettings();
public void OpenTrafficHistory() => _bizHelper.OpenTrafficHistory();
public void CleanMemory() => _bizHelper.CleanMemory();
// ==== 任务栏显示 ====
private TaskbarForm? _taskbar;
public void ToggleTaskbar(bool show)
{
if (show)
{
if (_taskbar != null && !_taskbar.IsDisposed)
{
if (_taskbar.TargetDevice != _cfg.TaskbarMonitorDevice)
{
_taskbar.Close();
_taskbar.Dispose();
_taskbar = null;
}
}
if (_taskbar == null || _taskbar.IsDisposed)
{
if (_ui != null)
{
_taskbar = new TaskbarForm(_cfg, _ui, this);
_taskbar.Show();
}
}
else
{
if (!_taskbar.Visible)
{
_taskbar.Show();
_taskbar.ReloadLayout();
}
}
}
else
{
if (_taskbar != null)
{
_taskbar.Close();
_taskbar.Dispose();
_taskbar = null;
}
}
}
// ========== 构造函数 ==========
public MainForm()
{
// 语言加载
if (string.IsNullOrEmpty(_cfg.Language))
{
string sysLang = System.Globalization.CultureInfo.CurrentUICulture.TwoLetterISOLanguageName.ToLower();
string langPath = Path.Combine(AppContext.BaseDirectory, "resources/lang", $"{sysLang}.json");
_cfg.Language = File.Exists(langPath) ? sysLang : "en";
}
LanguageManager.Load(_cfg.Language);
_cfg.SyncToLanguage();
// 1. 初始化业务
// ★★★ Fix: 初始化全局 DPI 缩放系数,防止未打开设置面板时弹窗排版异常 ★★★
UIUtils.ScaleFactor = this.DeviceDpi / 96f;
TrafficLogger.Load();
src.Plugins.PluginManager.Instance.LoadPlugins(Path.Combine(AppContext.BaseDirectory, "resources", "plugins"));
src.Plugins.PluginManager.Instance.Start();
_ui = new UIController(_cfg, this);
new src.WebServer.LiteWebServer(_cfg);
// 5. 设置背景色 (这是关键!解耦时漏掉了这行,导致背景是系统默认色而非透明或皮肤色)
BackColor = ThemeManager.ParseColor(ThemeManager.Current.Color.Background);
// 2. 初始化双助手
_winHelper = new MainFormWinHelper(this);
//资源管理器重启监听
_wmTaskbarCreated = MainFormWinHelper.RegisterTaskbarCreatedMessage();
// ★★★ 关键修复:补全 SetStyle 调用,开启透明支持 ★★★
// 原始代码中这里调用了 SetStyle(ControlStyles.SupportsTransparentBackColor, true);
// 解耦时漏掉了这一行,导致背景无法透明,显示为黑色或系统默认色
SetStyle(ControlStyles.SupportsTransparentBackColor, true);
SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer | ControlStyles.ResizeRedraw, true);
_winHelper.InitializeStyle(_cfg.TopMost, _cfg.ClickThrough);
// 原始代码还原:这里需要手动设置 Opacity = 0,
// 但是要在构造函数里设置,和原始代码保持一致的位置
this.Opacity = 0;
_bizHelper = new MainFormBizHelper(this, _cfg, _ui, _winHelper);
_bizHelper.Initialize();
// === 渐入透明度 (还原原始代码逻辑) ===
// 原始代码是在构造函数末尾启动 Task
// 之前解耦时移到了 OnShown 里,这可能导致时序差异(OnShown 之前会有一瞬间的默认绘制)
_winHelper.StartFadeIn(_cfg.Opacity);
// 3. 事件绑定
BindEvents();
}
private void BindEvents()
{
// 拖拽
MouseDown += (_, e) =>
{
if (e.Button == MouseButtons.Left)
{
_ui?.SetDragging(true);
_uiDragging = true;
_bizHelper.IsDragging = true;
_dragOffset = e.Location;
}
};
MouseMove += (_, e) =>
{
if (e.Button == MouseButtons.Left)
{
if (Math.Abs(e.X - _dragOffset.X) + Math.Abs(e.Y - _dragOffset.Y) < 1) return;
Location = new Point(Left + e.X - _dragOffset.X, Top + e.Y - _dragOffset.Y);
}
};
MouseUp += (_, e) =>
{
if (e.Button == MouseButtons.Left)
{
_ui?.SetDragging(false);
_uiDragging = false;
_bizHelper.IsDragging = false;
_bizHelper.ClampToScreen();
_bizHelper.SavePos();
}
};
// 双击
this.DoubleClick += (_, __) => _bizHelper.HandleDoubleClick();
// DPI / Resize
this.Resize += (_, __) => _winHelper.ApplyRoundedCorners();
}
public void ShowMainWindow()
{
this.Show();
this.WindowState = FormWindowState.Normal;
this.Activate();
_cfg.HideMainForm = false;
_cfg.Save();
_bizHelper.ForceShow();
_bizHelper.RebuildMenus();
}
public void HideMainWindow()
{
this.Hide();
_cfg.HideMainForm = true;
_cfg.Save();
_bizHelper.RebuildMenus();
}
protected override void WndProc(ref Message m)
{
if (m.Msg == _wmTaskbarCreated && _wmTaskbarCreated != 0)
{
// [Fix] Explorer 重启后,子窗口 TaskbarForm 会被销毁或失效。
// 必须由主窗口感知并重建 TaskbarForm,才能恢复显示。
if (_cfg.ShowTaskbar)
{
// 延迟执行,确保 Explorer 初始化基本完成,同时避免阻塞消息泵
this.BeginInvoke(new Action(async () =>
{
try
{
await Task.Delay(3000); // 等待3秒让Explorer缓口气
ToggleTaskbar(false); // 彻底销毁旧实例
ToggleTaskbar(true); // 创建新实例(新实例自带重试机制)
}
catch { }
}));
}
}
if (m.Msg == WM_DISPLAYCHANGE)
{
// [Fix #288] 分辨率改变后,延迟执行位置恢复,确保 Screen.AllScreens 已完全更新
// 增加防抖机制,避免短时间内多次触发
_displayChangeCts?.Cancel();
_displayChangeCts = new System.Threading.CancellationTokenSource();
var token = _displayChangeCts.Token;
Task.Delay(500, token).ContinueWith(t =>
{
if (!t.IsCanceled)
{
this.BeginInvoke(new Action(() => _bizHelper?.RestorePos()));
}
});
}
base.WndProc(ref m);
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
_ui?.Render(e.Graphics);
}
protected override void OnPaintBackground(PaintEventArgs e) { }
protected override void OnDpiChanged(DpiChangedEventArgs e)
{
base.OnDpiChanged(e);
_ui?.ApplyTheme(_cfg.Skin);
_winHelper.ApplyRoundedCorners();
this.Invalidate();
}
protected override void OnShown(EventArgs e)
{
base.OnShown(e);
// 恢复可见性
if (_cfg.HideMainForm) this.Hide();
this.Update();
// 恢复位置
_bizHelper.RestorePos();
// 确保渲染尺寸正确 (横屏模式)
if (_cfg.HorizontalMode && _ui != null)
{
this.Size = new Size(this.Width, this.Height);
}
// 移除了 StartFadeIn 调用,因为它已经还原回构造函数了
_winHelper.ApplyRoundedCorners();
_bizHelper.KeepVisible(3.0); // 启动保护期
if (_cfg.ShowTaskbar) ToggleTaskbar(true);
// 启动 WebServer
if (_cfg.WebServerEnabled)
{
if (src.WebServer.LiteWebServer.Instance?.Start(out string err) == false)
{
ShowNotification("WebServer Error",
(_cfg.Language == "zh" ? "Web服务启动失败: " : "Web Server Failed: ") + err,
ToolTipIcon.Error);
}
}
// 这样既检查了驱动,也检查了更新,以及置顶 透明度 穿透 等,而且时机完美(窗口显示后)
if (_bizHelper != null)
{
_ = _bizHelper.RunStartupChecksAsync();
}
// [Fix] 置顶守护:周期性检测并恢复被虚拟桌面切换、全屏游戏等夺走的置顶状态
StartTopMostGuard();
}
protected override void OnFormClosed(FormClosedEventArgs e)
{
_topMostGuardTimer?.Stop();
_topMostGuardTimer?.Dispose();
_cfg.Save();
TrafficLogger.Save();
src.WebServer.LiteWebServer.Instance?.Stop();
base.OnFormClosed(e);
_ui?.Dispose();
_bizHelper.Dispose();
}
private void StartTopMostGuard()
{
if (_topMostGuardTimer != null) return;
_topMostGuardTimer = new System.Windows.Forms.Timer { Interval = 3000 };
_topMostGuardTimer.Tick += (_, __) =>
{
if (_cfg.TopMost && Visible)
{
// 如果本应用有其他活动窗口(如设置面板),跳过强制置顶以免遮挡
var activeForm = Form.ActiveForm;
if (activeForm != null && activeForm != this)
return;
_winHelper.ReapplyTopMost();
}
};
_topMostGuardTimer.Start();
}
}
}