-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMainForm.cs
More file actions
386 lines (340 loc) · 17.2 KB
/
Copy pathMainForm.cs
File metadata and controls
386 lines (340 loc) · 17.2 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
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading;
using System.Windows.Forms;
using Microsoft.Web.WebView2.Core;
using Microsoft.Web.WebView2.WinForms;
using AutoClicker.Core;
using AutoClicker.Input;
using AutoClicker.UI;
namespace AutoClicker
{
public class MainForm : Form
{
private WebView2 webView;
private NotifyIcon trayIcon;
private ContextMenuStrip trayMenu;
// 🔧 Поле для хранения иконки, чтобы использовать в обоих местах
private Icon _appIcon;
private readonly MouseController _mouse = new MouseController();
private readonly KeyboardController _keyboard = new KeyboardController();
private readonly ClickerManager _manager;
private readonly HotkeyListener _hotkeys = new HotkeyListener();
private CancellationTokenSource _hotkeyCts;
private readonly List<ClickerProfile> _profiles = new List<ClickerProfile>();
private readonly Dictionary<Guid, bool> _previousHotkeyStates = new Dictionary<Guid, bool>();
private readonly Dictionary<string, KeyCombination> _pendingCaptures = new Dictionary<string, KeyCombination>();
private DateTime _captureCooldownUntil = DateTime.MinValue;
private static readonly JsonSerializerOptions _jsonOptions = new JsonSerializerOptions
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
WriteIndented = false
};
public MainForm()
{
// 🔧 ЗАГРУЗКА ИКОНКИ (ОДИН РАЗ, в MemoryStream)
_appIcon = LoadAppIcon();
// Применяем к окну
this.Icon = _appIcon;
_manager = new ClickerManager(_mouse, _keyboard);
InitializeComponent();
InitializeTray();
InitializeWebView();
WireBackendEvents();
}
// 🔧 Метод загрузки иконки с фолбэком
private Icon LoadAppIcon()
{
try
{
var assembly = Assembly.GetExecutingAssembly();
string resourceName = "AutoClicker.Resources.app_icon.ico";
using (Stream stream = assembly.GetManifestResourceStream(resourceName))
{
if (stream != null)
{
// Читаем в MemoryStream, чтобы можно было переиспользовать
using var memory = new MemoryStream();
stream.CopyTo(memory);
memory.Position = 0;
return new Icon(memory, 32, 32);
}
}
}
catch (Exception ex)
{
Console.WriteLine($"[Icon Load Error] {ex.Message}");
}
// Фолбэк: сначала попробуем из .exe, потом системная
try
{
var exeIcon = Icon.ExtractAssociatedIcon(Application.ExecutablePath);
if (exeIcon != null) return exeIcon;
}
catch { }
return SystemIcons.Application;
}
private void InitializeComponent()
{
this.Text = "⚡ AutoClicker V2 by BestArmor";
this.Size = new Size(1100, 750);
this.MinimumSize = new Size(900, 600);
this.StartPosition = FormStartPosition.CenterScreen;
this.BackColor = Color.FromArgb(10, 10, 21);
this.ShowInTaskbar = true; // 🔧 Важно: показывать в панели задач
this.Resize += MainForm_Resize;
this.FormClosing += MainForm_FormClosing;
webView = new WebView2 { Dock = DockStyle.Fill };
this.Controls.Add(webView);
}
private void InitializeTray()
{
trayMenu = new ContextMenuStrip();
trayMenu.Items.Add("🔼 Restore Window", null, (s, e) => ShowForm());
trayMenu.Items.Add(new ToolStripSeparator());
trayMenu.Items.Add("❌ Exit AutoClicker", null, (s, e) => {
trayIcon.Visible = false;
trayIcon.Dispose();
Environment.Exit(0); // Полный выход, минуя FormClosing
});
// 🔧 Создаём trayIcon С ИКОНКОЙ (один раз, правильно)
trayIcon = new NotifyIcon
{
Icon = _appIcon, // Используем уже загруженную иконку
ContextMenuStrip = trayMenu,
Text = "AutoClicker V2 by BestArmor",
Visible = false // Скрыт, пока не свернули
};
trayIcon.DoubleClick += (s, e) => ShowForm();
}
private void ShowForm()
{
this.Show();
this.WindowState = FormWindowState.Normal;
this.ShowInTaskbar = true;
this.Activate();
trayIcon.Visible = false;
}
private void MainForm_Resize(object sender, EventArgs e)
{
if (this.WindowState == FormWindowState.Minimized)
{
// 🔧 ПРАВИЛЬНОЕ сворачивание в трей
this.Hide(); // Прячем окно
this.ShowInTaskbar = false; // Убираем из панели задач
trayIcon.Visible = true; // Показываем в трее
trayIcon.ShowBalloonTip(2000, "AutoClicker V2",
"Работает в фоне. Двойной клик для восстановления.",
ToolTipIcon.Info);
}
}
private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
{
// Сворачиваем в трей вместо закрытия
if (e.CloseReason == CloseReason.UserClosing)
{
e.Cancel = true;
this.WindowState = FormWindowState.Minimized;
}
}
private async void InitializeWebView()
{
try
{
var env = await CoreWebView2Environment.CreateAsync();
await webView.EnsureCoreWebView2Async(env);
string appDir = AppDomain.CurrentDomain.BaseDirectory;
string wwwrootPath = Path.Combine(appDir, "wwwroot");
if (!Directory.Exists(wwwrootPath))
{
MessageBox.Show($"Папка wwwroot не найдена!\n{wwwrootPath}", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
webView.CoreWebView2.SetVirtualHostNameToFolderMapping("app.local", wwwrootPath, CoreWebView2HostResourceAccessKind.Allow);
webView.CoreWebView2.WebMessageReceived += OnWebMessageReceived;
webView.CoreWebView2.Settings.AreDevToolsEnabled = true;
webView.CoreWebView2.Navigate("https://app.local/index.html");
}
catch (Exception ex) { MessageBox.Show($"Ошибка: {ex.Message}", "Ошибка"); }
}
private void OnWebMessageReceived(object sender, CoreWebView2WebMessageReceivedEventArgs e)
{
try
{
string rawJson = e.TryGetWebMessageAsString();
using var doc = JsonDocument.Parse(rawJson);
var root = doc.RootElement;
if (root.ValueKind != JsonValueKind.Object || !root.TryGetProperty("type", out var typeProp)) return;
string type = typeProp.GetString();
switch (type)
{
case "addProfile": AddProfile(); break;
case "removeProfile":
if (root.TryGetProperty("id", out var idProp)) RemoveProfile(Guid.Parse(idProp.GetString()));
break;
case "updateProfile":
if (root.TryGetProperty("profile", out var pe) && pe.ValueKind == JsonValueKind.Object) UpdateProfileFromJson(pe);
break;
case "toggleProfile":
if (root.TryGetProperty("id", out var tid))
{
var p = _profiles.FirstOrDefault(x => x.Id == Guid.Parse(tid.GetString()));
if (p != null) _manager.ToggleProfile(p);
}
break;
case "startCapture":
if (root.TryGetProperty("target", out var tprop)) StartKeyCapture(tprop.GetString());
break;
case "updateAppSetting":
if (root.TryGetProperty("opacity", out var op)) this.Invoke(() => this.Opacity = Math.Clamp(op.GetDouble(), 0.3, 1.0));
if (root.TryGetProperty("topmost", out var tm)) this.Invoke(() => this.TopMost = tm.GetBoolean());
break;
}
}
catch (Exception ex) { Console.WriteLine($"[C# Error] {ex.Message}"); SendLogMessage($"❌ Error: {ex.Message}"); }
}
private void AddProfile()
{
try
{
var profile = new ClickerProfile { Name = $"Profile {_profiles.Count + 1}", Mode = ClickerMode.MouseLeftClick, IntervalMs = 100 };
_profiles.Add(profile);
SendJsonMessage(new MessageDto { Type = "profileAdded", Profile = ProfileToDto(profile) });
SendLogMessage($"➕ Profile created: {profile.Name}");
}
catch (Exception ex) { SendLogMessage($"❌ Create error: {ex.Message}"); }
}
private void RemoveProfile(Guid id)
{
_manager.StopProfile(id);
var profile = _profiles.FirstOrDefault(p => p.Id == id);
if (profile != null)
{
string name = profile.Name;
_profiles.Remove(profile);
_previousHotkeyStates.Remove(id);
SendJsonMessage(new MessageDto { Type = "profileRemoved", Id = id.ToString() });
SendLogMessage($"🗑 Profile removed: {name}");
}
}
private void UpdateProfileFromJson(JsonElement json)
{
try
{
if (!json.TryGetProperty("id", out var idProp)) return;
var id = Guid.Parse(idProp.GetString());
var profile = _profiles.FirstOrDefault(p => p.Id == id);
if (profile == null) return;
if (json.TryGetProperty("name", out var n)) profile.Name = n.GetString();
if (json.TryGetProperty("interval", out var i)) profile.IntervalMs = i.GetInt32();
if (json.TryGetProperty("mode", out var m))
{
string mode = m.GetString();
if (mode == "mouse")
{
if (json.TryGetProperty("mouseType", out var mt)) profile.Mode = mt.GetString() switch { "right" => ClickerMode.MouseRightClick, "double" => ClickerMode.MouseDoubleClick, _ => ClickerMode.MouseLeftClick };
}
else
{
if (json.TryGetProperty("keyboardSub", out var ks)) profile.Mode = ks.GetString() switch { "hold" => ClickerMode.KeyboardHold, "toggle" => ClickerMode.KeyboardToggle, _ => ClickerMode.KeyboardPress };
else profile.Mode = ClickerMode.KeyboardPress;
}
}
var pk = GetPendingCombo("key"); if (pk != null) profile.KeyCombo = pk;
var ph = GetPendingCombo("hotkey"); if (ph != null) profile.Hotkey = ph;
SendJsonMessage(new MessageDto { Type = "profileUpdated", Profile = ProfileToDto(profile) });
}
catch (Exception ex) { Console.WriteLine($"[C# UpdateProfileFromJson Error] {ex.Message}"); }
}
private void StartKeyCapture(string target)
{
using (var form = new KeyCaptureForm())
{
var result = form.ShowDialog(this);
if (result == DialogResult.OK)
{
_pendingCaptures[target] = form.Result;
_captureCooldownUntil = DateTime.Now.AddMilliseconds(500);
foreach (var k in _previousHotkeyStates.Keys.ToList()) _previousHotkeyStates[k] = true;
SendJsonMessage(new MessageDto { Type = "keyCaptured", Combo = form.Result.DisplayName, Target = target });
SendLogMessage($"🎯 Key captured: {form.Result.DisplayName}");
}
}
}
private KeyCombination GetPendingCombo(string target)
{
if (_pendingCaptures.TryGetValue(target, out var combo)) { _pendingCaptures.Remove(target); return combo; }
return null;
}
private void WireBackendEvents()
{
_manager.OnProfileLog += (id, msg) => this.Invoke(() => SendLogMessage(msg));
_manager.OnProfileStateChanged += (id, running) =>
{
var profile = _profiles.FirstOrDefault(p => p.Id == id);
if (profile != null)
{
profile.IsRunning = running;
this.Invoke(() => SendJsonMessage(new MessageDto { Type = "profileStateChanged", Id = id.ToString(), Running = running }));
}
};
_hotkeyCts = _hotkeys.StartListening();
_hotkeys.OnToggleClicker += () => this.Invoke(() =>
{
if (DateTime.Now < _captureCooldownUntil) return;
var first = _profiles.FirstOrDefault();
if (first != null) { _manager.ToggleProfile(first); SendLogMessage($"🎯 F6 → {first.Name}"); }
});
_hotkeys.OnStopAll += () => this.Invoke(() => { _manager.StopAll(); SendLogMessage("⚠ Emergency stop (F7)"); });
var hotkeyCheckTimer = new System.Windows.Forms.Timer { Interval = 50 };
hotkeyCheckTimer.Tick += HotkeyCheckTimer_Tick;
hotkeyCheckTimer.Start();
}
private void HotkeyCheckTimer_Tick(object sender, EventArgs e)
{
if (DateTime.Now < _captureCooldownUntil) return;
foreach (var profile in _profiles.ToList())
{
if (profile.Hotkey.IsEmpty) continue;
bool pressed = profile.Hotkey.IsPressed();
bool was = _previousHotkeyStates.TryGetValue(profile.Id, out var prev) && prev;
if (pressed && !was) { _manager.ToggleProfile(profile); SendLogMessage($"🎯 [{profile.Hotkey.DisplayName}] → {profile.Name}"); }
_previousHotkeyStates[profile.Id] = pressed;
}
}
private void SendLogMessage(string message) => SendJsonMessage(new MessageDto { Type = "log", Message = message });
private void SendJsonMessage(MessageDto message)
{
if (webView?.CoreWebView2 == null) return;
try { webView.CoreWebView2.PostWebMessageAsJson(JsonSerializer.Serialize(message, _jsonOptions)); }
catch (Exception ex) { Console.WriteLine($"[C# Send Error] {ex.Message}"); }
}
private ProfileDto ProfileToDto(ClickerProfile p) => new ProfileDto
{
Id = p.Id.ToString(), Name = p.Name,
Mode = p.Mode switch { ClickerMode.MouseLeftClick => "mouse", ClickerMode.MouseRightClick => "mouse", ClickerMode.MouseDoubleClick => "mouse", _ => "keyboard" },
MouseType = p.Mode switch { ClickerMode.MouseRightClick => "right", ClickerMode.MouseDoubleClick => "double", _ => "left" },
KeyboardSub = p.Mode switch { ClickerMode.KeyboardPress => "press", ClickerMode.KeyboardHold => "hold", ClickerMode.KeyboardToggle => "toggle", _ => "press" },
KeyCombo = p.KeyCombo.IsEmpty ? "" : p.KeyCombo.DisplayName,
Interval = p.IntervalMs, Hotkey = p.Hotkey.IsEmpty ? "" : p.Hotkey.DisplayName, IsRunning = p.IsRunning
};
protected override void OnFormClosed(FormClosedEventArgs e)
{
trayIcon?.Dispose();
_appIcon?.Dispose();
_manager.Dispose();
_hotkeyCts?.Cancel();
_hotkeys.Dispose();
base.OnFormClosed(e);
}
private class MessageDto { public string Type { get; set; } public string Message { get; set; } public string Id { get; set; } public bool? Running { get; set; } public ProfileDto Profile { get; set; } public string Combo { get; set; } public string Target { get; set; } }
private class ProfileDto { public string Id { get; set; } public string Name { get; set; } public string Mode { get; set; } public string MouseType { get; set; } public string KeyboardSub { get; set; } public string KeyCombo { get; set; } public int Interval { get; set; } public string Hotkey { get; set; } public bool IsRunning { get; set; } }
}
}