-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMainForm.cs
More file actions
1601 lines (1416 loc) · 61.1 KB
/
MainForm.cs
File metadata and controls
1601 lines (1416 loc) · 61.1 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
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.IO;
using System.Drawing;
using System.Threading;
using System.Reflection;
using System.Windows.Forms;
using System.Threading.Tasks;
using System.Xml.Serialization;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Text;
using SharpDX.XInput;
namespace D4Automator
{
public partial class MainForm : Form
{
[DllImport("user32.dll")]
static extern void keybd_event(byte bVk, byte bScan, uint dwFlags, UIntPtr dwExtraInfo);
[DllImport("user32.dll")]
public static extern void mouse_event(int dwFlags, int dx, int dy, int cButtons, int dwExtraInfo);
[DllImport("user32.dll")]
private static extern bool RegisterHotKey(IntPtr hWnd, int id, uint fsModifiers, uint vk);
[DllImport("user32.dll")]
private static extern bool UnregisterHotKey(IntPtr hWnd, int id);
[DllImport("user32.dll")]
static extern IntPtr GetForegroundWindow();
private const int KEYEVENTF_KEYUP = 0x0002;
private const int MOUSEEVENTF_LEFTDOWN = 0x0002;
private const int MOUSEEVENTF_LEFTUP = 0x0004;
private const int MOUSEEVENTF_RIGHTDOWN = 0x0008;
private const int MOUSEEVENTF_RIGHTUP = 0x0010;
private const int MOUSEEVENTF_MIDDLEDOWN = 0x0020;
private const int MOUSEEVENTF_MIDDLEUP = 0x0040;
private const int MOUSEEVENTF_XDOWN = 0x0080;
private const int MOUSEEVENTF_XUP = 0x0100;
private const int XBUTTON1 = 0x0001;
private const int XBUTTON2 = 0x0002;
private const int HOTKEY_ID = 9000;
private const int MOUSEMOVE_HOTKEY_ID = 9001;
private bool isRunning = false;
private Settings settings;
private string settingsPath;
private CancellationTokenSource cancellationTokenSource;
private HashSet<Keys> heldKeys = new HashSet<Keys>();
private HashSet<MouseButtons> heldMouseButtons = new HashSet<MouseButtons>();
private Controller controller;
private System.Windows.Forms.Timer controllerCheckTimer;
private const float DEAD_ZONE = 0.1f; // Adjust as needed
private bool wasAutomationRunning = false;
private bool isMoving = false;
private System.Windows.Forms.Timer moveTimer;
// Hordes elliptical movement configuration - adjust these values to troubleshoot
private int ELLIPSE_RADIUS_X => (int)(settings.HordesCircleSize * 1.78); // Horizontal radius in pixels (16:9 aspect ratio)
private int ELLIPSE_RADIUS_Y => settings.HordesCircleSize; // Vertical radius in pixels
private double CIRCLE_SPEED => settings.HordesCircleSpeed; // Degrees to move per tick (smaller = slower movement)
private int CIRCLE_TIMER_INTERVAL => settings.HordesTimerInterval; // Milliseconds between movements (higher = slower)
private double currentAngle = 0; // Current angle in the circle (0-360 degrees)
private Point circleCenter; // Center point of the circle
private int circleDirection = 1; // 1 for clockwise, -1 for counter-clockwise
private double degreesInCurrentDirection = 0; // Track degrees traveled since last reversal
private const double DEGREES_BEFORE_REVERSAL = 540; // 1.5 full circles (360 * 1.5)
private OverlayForm overlayForm; // Overlay to show automation status
private bool hasUnsavedChanges = false;
private string currentFileName = string.Empty;
private string recentFilesPath;
public MainForm()
{
InitializeComponent();
InitializeSettings();
InitializeKeyMappings();
RegisterGlobalHotkey();
ApplyDarkMode();
AttachEventHandlers();
SetFormTitle();
UpdateLabels();
InitializeControllerDetection();
InitializeOverlay();
// Update recent files menu after form is loaded
this.Load += MainForm_Load;
}
private void MainForm_Load(object sender, EventArgs e)
{
UpdateRecentFilesMenu();
}
private void InitializeControllerDetection()
{
// Assumes the first controller
controller = new Controller(UserIndex.One);
// Check if controller is connected
if (controller.IsConnected)
{
controllerCheckTimer = new System.Windows.Forms.Timer();
controllerCheckTimer.Interval = 50; // Check every 50ms
controllerCheckTimer.Tick += ControllerCheckTimer_Tick;
controllerCheckTimer.Start();
}
}
private void ControllerCheckTimer_Tick(object sender, EventArgs e)
{
try
{
if (controller.IsConnected)
{
var state = controller.GetState();
bool controllerMoved = IsControllerMoved(state);
if (controllerMoved)
{
if (isRunning)
{
StopAutomation();
wasAutomationRunning = true;
}
}
else if (wasAutomationRunning)
{
StartAutomation();
wasAutomationRunning = false;
}
}
}
catch (Exception)
{
// Ignore controller read errors to prevent crashes
}
}
private bool IsControllerMoved(State state)
{
// Check analog sticks (cast to int to avoid overflow when value is short.MinValue)
bool leftStickMoved = Math.Abs((int)state.Gamepad.LeftThumbX) > short.MaxValue * DEAD_ZONE ||
Math.Abs((int)state.Gamepad.LeftThumbY) > short.MaxValue * DEAD_ZONE;
bool rightStickMoved = Math.Abs((int)state.Gamepad.RightThumbX) > short.MaxValue * DEAD_ZONE ||
Math.Abs((int)state.Gamepad.RightThumbY) > short.MaxValue * DEAD_ZONE;
// Check digital pad
bool dPadPressed = state.Gamepad.Buttons.HasFlag(GamepadButtonFlags.DPadUp) ||
state.Gamepad.Buttons.HasFlag(GamepadButtonFlags.DPadDown) ||
state.Gamepad.Buttons.HasFlag(GamepadButtonFlags.DPadLeft) ||
state.Gamepad.Buttons.HasFlag(GamepadButtonFlags.DPadRight);
return leftStickMoved || rightStickMoved || dPadPressed;
}
private void InitializeKeyMappings()
{
keyMappings = new Dictionary<string, Action>();
UpdateKeyMappings();
}
private void AttachEventHandlers()
{
nudSkill1.ValueChanged += nudSkill1_ValueChanged;
nudSkill2.ValueChanged += nudSkill2_ValueChanged;
nudSkill3.ValueChanged += nudSkill3_ValueChanged;
nudSkill4.ValueChanged += nudSkill4_ValueChanged;
nudPrimaryAttack.ValueChanged += nudRightClick_ValueChanged;
nudSecondaryAttack.ValueChanged += nudLeftClick_ValueChanged;
nudMove.ValueChanged += nudMove_ValueChanged;
nudPotion.ValueChanged += nudPotion_ValueChanged;
nudDodge.ValueChanged += nudDodge_ValueChanged;
// Add KeyDown event handlers to detect immediate changes
nudSkill1.KeyDown += NumericUpDown_KeyDown;
nudSkill2.KeyDown += NumericUpDown_KeyDown;
nudSkill3.KeyDown += NumericUpDown_KeyDown;
nudSkill4.KeyDown += NumericUpDown_KeyDown;
nudPrimaryAttack.KeyDown += NumericUpDown_KeyDown;
nudSecondaryAttack.KeyDown += NumericUpDown_KeyDown;
nudMove.KeyDown += NumericUpDown_KeyDown;
nudPotion.KeyDown += NumericUpDown_KeyDown;
nudDodge.KeyDown += NumericUpDown_KeyDown;
}
private void NumericUpDown_KeyDown(object sender, KeyEventArgs e)
{
// Mark as changed when user types in numeric controls
// This will be more responsive than waiting for ValueChanged
if (char.IsDigit((char)e.KeyCode) || e.KeyCode == Keys.Back || e.KeyCode == Keys.Delete)
{
// Use a timer to mark as changed after a short delay
var timer = new System.Windows.Forms.Timer();
timer.Interval = 100; // Very short delay
timer.Tick += (s, args) =>
{
timer.Stop();
timer.Dispose();
CheckForPendingChanges();
};
timer.Start();
}
}
private void SetFormTitle()
{
Version version = Assembly.GetExecutingAssembly().GetName().Version;
string baseTitle = $"D4 Automator v{version.Major}.{version.Minor}.{version.Build}";
if (!string.IsNullOrEmpty(currentFileName))
{
baseTitle += $" - {Path.GetFileName(currentFileName)}";
}
if (hasUnsavedChanges)
{
baseTitle += "*";
}
this.Text = baseTitle;
}
private void MarkAsChanged()
{
if (!hasUnsavedChanges)
{
hasUnsavedChanges = true;
SetFormTitle();
}
}
private void MarkAsSaved()
{
if (hasUnsavedChanges)
{
hasUnsavedChanges = false;
SetFormTitle();
}
}
private void InitializeSettings()
{
string executablePath = Assembly.GetExecutingAssembly().Location;
string executableDirectory = Path.GetDirectoryName(executablePath);
settingsPath = Path.Combine(executableDirectory, "D4AutomatorSettings.xml");
recentFilesPath = Path.Combine(executableDirectory, "RecentFiles.txt");
if (File.Exists(settingsPath))
{
LoadSettings();
}
else
{
CreateDefaultSettings();
}
ApplySettingsToControls();
AutoLoadLastConfiguration();
}
private void CreateDefaultSettings()
{
settings = new Settings
{
Skill1Delay = 3000,
Skill2Delay = 3000,
Skill3Delay = 3000,
Skill4Delay = 3000,
PrimaryAttackDelay = 400,
SecondaryAttackDelay = 400,
MoveDelay = 400,
PotionDelay = 2000,
DodgeDelay = 0
};
SaveSettings();
}
private void LoadSettings()
{
XmlSerializer serializer = new XmlSerializer(typeof(Settings));
using (FileStream stream = new FileStream(settingsPath, FileMode.Open))
{
settings = (Settings)serializer.Deserialize(stream);
}
UpdateKeyMappings();
UpdateLabels();
}
private void SaveSettings()
{
XmlSerializer serializer = new XmlSerializer(typeof(Settings));
using (FileStream stream = new FileStream(settingsPath, FileMode.Create))
{
serializer.Serialize(stream, settings);
}
}
private void AutoLoadLastConfiguration()
{
if (!string.IsNullOrEmpty(settings.LastLoadedConfigFile) && File.Exists(settings.LastLoadedConfigFile))
{
try
{
string jsonContent = File.ReadAllText(settings.LastLoadedConfigFile);
var loadedSettings = DeserializeSettingsFromJson(jsonContent);
// Preserve the LastLoadedConfigFile value
loadedSettings.LastLoadedConfigFile = settings.LastLoadedConfigFile;
settings = loadedSettings;
currentFileName = settings.LastLoadedConfigFile;
ApplySettingsToControls();
UpdateKeyMappings();
UpdateLabels();
MarkAsSaved(); // Mark as saved since we just loaded
}
catch
{
// If loading fails, just continue with current settings
// Don't show error message on startup
}
}
}
private void ApplySettingsToControls()
{
nudSkill1.Value = settings.Skill1Delay;
nudSkill2.Value = settings.Skill2Delay;
nudSkill3.Value = settings.Skill3Delay;
nudSkill4.Value = settings.Skill4Delay;
nudPrimaryAttack.Value = settings.PrimaryAttackDelay;
nudSecondaryAttack.Value = settings.SecondaryAttackDelay;
nudMove.Value = settings.MoveDelay;
nudPotion.Value = settings.PotionDelay;
nudDodge.Value = settings.DodgeDelay;
}
private void UpdateLabels()
{
lblSkill1.Text = $"Skill 1 ({GetDisplayTextForKey(settings.Skill1Action)}) Delay (ms):";
lblSkill2.Text = $"Skill 2 ({GetDisplayTextForKey(settings.Skill2Action)}) Delay (ms):";
lblSkill3.Text = $"Skill 3 ({GetDisplayTextForKey(settings.Skill3Action)}) Delay (ms):";
lblSkill4.Text = $"Skill 4 ({GetDisplayTextForKey(settings.Skill4Action)}) Delay (ms):";
lblPrimaryAttack.Text = $"Primary Attack ({GetDisplayTextForKey(settings.PrimaryAttackAction)}) Delay (ms):";
lblSecondaryAttack.Text = $"Secondary Attack ({GetDisplayTextForKey(settings.SecondaryAttackAction)}) Delay (ms):";
lblMove.Text = $"Move ({GetDisplayTextForKey(settings.MoveAction)}) Delay (ms):";
lblPotion.Text = $"Potion ({GetDisplayTextForKey(settings.PotionAction)}) Delay (ms):";
lblDodge.Text = $"Dodge ({GetDisplayTextForKey(settings.DodgeAction)}) Delay (ms):";
lblInstructions.Text = $"Press {GetDisplayTextForKey(settings.ToggleAutomationAction)} to start/stop automation.\r\nPress {GetDisplayTextForKey(settings.ToggleMouseMoveAction)} for automation + mouse move (Infernal Hordes).\r\n\r\nSet delay to 0 to disable an action.\r\nSet delay to 1 to keep button/key pressed.";
}
private string GetDisplayTextForKey(string keyString)
{
if (string.IsNullOrEmpty(keyString))
{
return string.Empty;
}
switch (keyString)
{
case "LeftClick":
return "Left Click";
case "RightClick":
return "Right Click";
case "MiddleClick":
return "Middle Click";
case "MouseBack":
return "Mouse Back";
case "MouseForward":
return "Mouse Forward";
default:
return keyString;
}
if (keyString.StartsWith("D") && keyString.Length == 2 && char.IsDigit(keyString[1]))
{
return keyString.Substring(1); // Remove the 'D' prefix for number keys
}
if (keyString.StartsWith("NumPad") && keyString.Length > 6)
{
return $"NumPad {keyString.Substring(6)}";
}
return keyString;
}
protected override void WndProc(ref Message m)
{
if (m.Msg == 0x0312) // WM_HOTKEY
{
// Automation toggle hotkey
if (m.WParam.ToInt32() == HOTKEY_ID)
{
ToggleAutomation();
}
// Mouse move + automation toggle hotkey
else if (m.WParam.ToInt32() == MOUSEMOVE_HOTKEY_ID)
{
ToggleAutomationWithMouseMove();
}
}
base.WndProc(ref m);
}
private void ToggleAutomationWithMouseMove()
{
// If regular automation is running, switch to hordes automation
if (isRunning && !isMoving)
{
// Start mouse movement (automation already running)
InitializeMouseMovement();
isMoving = true;
circleCenter = System.Windows.Forms.Cursor.Position;
currentAngle = 0;
circleDirection = 1;
degreesInCurrentDirection = 0;
moveTimer.Start();
UpdateOverlay();
}
// If hordes automation is already running, stop everything
else if (isRunning && isMoving)
{
StopAutomation();
wasAutomationRunning = false;
isMoving = false;
moveTimer?.Stop();
UpdateOverlay();
}
// If nothing is running, start hordes automation
else
{
StartAutomation();
wasAutomationRunning = false;
InitializeMouseMovement();
isMoving = true;
circleCenter = System.Windows.Forms.Cursor.Position;
currentAngle = 0;
circleDirection = 1;
degreesInCurrentDirection = 0;
moveTimer.Start();
UpdateOverlay();
}
}
private void InitializeMouseMovement()
{
if (moveTimer == null)
{
moveTimer = new System.Windows.Forms.Timer();
moveTimer.Interval = CIRCLE_TIMER_INTERVAL;
moveTimer.Tick += MoveTimer_Tick;
}
}
private void MoveTimer_Tick(object sender, EventArgs e)
{
if (!isMoving) return;
// Convert angle to radians for calculation
double angleInRadians = currentAngle * (Math.PI / 180.0);
// Calculate the new position on the ellipse (16:9 aspect ratio)
int newX = circleCenter.X + (int)(ELLIPSE_RADIUS_X * Math.Cos(angleInRadians));
int newY = circleCenter.Y + (int)(ELLIPSE_RADIUS_Y * Math.Sin(angleInRadians));
// Move cursor to the new position
System.Windows.Forms.Cursor.Position = new Point(newX, newY);
// Increment the angle for the next tick (multiply by direction for reversal)
currentAngle += CIRCLE_SPEED * circleDirection;
degreesInCurrentDirection += CIRCLE_SPEED;
// Normalize angle to stay within 0-360 range
if (currentAngle >= 360)
{
currentAngle -= 360;
}
else if (currentAngle < 0)
{
currentAngle += 360;
}
// Reverse direction after 1.5 circles (540 degrees)
if (degreesInCurrentDirection >= DEGREES_BEFORE_REVERSAL)
{
circleDirection *= -1;
degreesInCurrentDirection = 0;
}
}
private void ToggleAutomation()
{
// If hordes automation is running, switch to regular automation
if (isRunning && isMoving)
{
// Stop mouse movement but keep automation running
isMoving = false;
moveTimer?.Stop();
UpdateOverlay();
}
// If regular automation is already running, stop it
else if (isRunning && !isMoving)
{
StopAutomation();
wasAutomationRunning = false;
UpdateOverlay();
}
// If nothing is running, start regular automation
else
{
StartAutomation();
wasAutomationRunning = false;
UpdateOverlay();
}
}
private async void StartAutomation()
{
isRunning = true;
cancellationTokenSource = new CancellationTokenSource();
try
{
await RunAutomation(cancellationTokenSource.Token);
}
catch (OperationCanceledException)
{
// Automation was cancelled, do nothing
}
finally
{
isRunning = false;
}
}
private void StopAutomation()
{
if (isRunning)
{
cancellationTokenSource?.Cancel();
isRunning = false;
ReleaseHeldInputs();
}
}
private async Task RunAutomation(CancellationToken cancellationToken)
{
var tasks = new List<Task>
{
RunActionLoop(settings.Skill1Delay, keyMappings["Skill1"], cancellationToken),
RunActionLoop(settings.Skill2Delay, keyMappings["Skill2"], cancellationToken),
RunActionLoop(settings.Skill3Delay, keyMappings["Skill3"], cancellationToken),
RunActionLoop(settings.Skill4Delay, keyMappings["Skill4"], cancellationToken),
RunActionLoop(settings.SecondaryAttackDelay, keyMappings["SecondaryAttack"], cancellationToken),
RunActionLoop(settings.PotionDelay, keyMappings["Potion"], cancellationToken),
RunActionLoop(settings.DodgeDelay, keyMappings["Dodge"], cancellationToken)
};
// Handle Primary Attack and Move together
if (settings.PrimaryAttackAction == settings.MoveAction)
{
// If both are the same, only run Primary Attack
tasks.Add(RunActionLoop(settings.PrimaryAttackDelay, keyMappings["PrimaryAttack"], cancellationToken));
}
else
{
// If different, run both
tasks.Add(RunActionLoop(settings.PrimaryAttackDelay, keyMappings["PrimaryAttack"], cancellationToken));
tasks.Add(RunActionLoop(settings.MoveDelay, keyMappings["Move"], cancellationToken));
}
while (!cancellationToken.IsCancellationRequested)
{
if (GetForegroundWindow() == this.Handle)
{
StopAutomation();
break;
}
await Task.Delay(50, cancellationToken); // Small delay to prevent excessive CPU usage
}
await Task.WhenAll(tasks);
}
private async Task RunActionLoop(int delay, Action action, CancellationToken cancellationToken)
{
bool buttonHeld = false;
while (!cancellationToken.IsCancellationRequested)
{
if (delay == 1 && !buttonHeld)
{
// Hold button pressed when delay is 1
action();
buttonHeld = true;
await Task.Delay(50, cancellationToken);
}
else if (delay > 1)
{
action();
await Task.Delay(delay, cancellationToken);
}
else
{
await Task.Delay(50, cancellationToken); // Small delay for actions with 0 delay
}
}
}
private void SimulateKeyPress(Keys key, bool holdKey = false)
{
if (InvokeRequired)
{
Invoke(new Action(() => SimulateKeyPress(key, holdKey)));
return;
}
byte vk = (byte)key;
keybd_event(vk, 0, 0, UIntPtr.Zero);
if (!holdKey)
{
keybd_event(vk, 0, KEYEVENTF_KEYUP, UIntPtr.Zero);
}
else
{
heldKeys.Add(key);
}
}
private void SimulateMouseClick(MouseButtons button, bool holdButton = false)
{
if (InvokeRequired)
{
Invoke(new Action(() => SimulateMouseClick(button, holdButton)));
return;
}
int downFlag;
int upFlag;
int mouseData = 0; // Required for X buttons
switch (button)
{
case MouseButtons.Left:
downFlag = MOUSEEVENTF_LEFTDOWN;
upFlag = MOUSEEVENTF_LEFTUP;
break;
case MouseButtons.Right:
downFlag = MOUSEEVENTF_RIGHTDOWN;
upFlag = MOUSEEVENTF_RIGHTUP;
break;
case MouseButtons.Middle:
downFlag = MOUSEEVENTF_MIDDLEDOWN;
upFlag = MOUSEEVENTF_MIDDLEUP;
break;
case MouseButtons.XButton1:
downFlag = MOUSEEVENTF_XDOWN;
upFlag = MOUSEEVENTF_XUP;
mouseData = XBUTTON1;
break;
case MouseButtons.XButton2:
downFlag = MOUSEEVENTF_XDOWN;
upFlag = MOUSEEVENTF_XUP;
mouseData = XBUTTON2;
break;
default:
// Unsupported mouse button
return;
}
mouse_event(downFlag, 0, 0, mouseData, 0);
if (!holdButton)
{
mouse_event(upFlag, 0, 0, mouseData, 0);
}
else
{
heldMouseButtons.Add(button);
}
}
private void ReleaseHeldInputs()
{
// Release all held keys
foreach (var key in heldKeys)
{
byte vk = (byte)key;
keybd_event(vk, 0, KEYEVENTF_KEYUP, UIntPtr.Zero);
}
heldKeys.Clear();
// Release all held mouse buttons
foreach (var button in heldMouseButtons)
{
int upFlag;
int mouseData = 0;
switch (button)
{
case MouseButtons.Left:
upFlag = MOUSEEVENTF_LEFTUP;
break;
case MouseButtons.Right:
upFlag = MOUSEEVENTF_RIGHTUP;
break;
case MouseButtons.Middle:
upFlag = MOUSEEVENTF_MIDDLEUP;
break;
case MouseButtons.XButton1:
upFlag = MOUSEEVENTF_XUP;
mouseData = XBUTTON1;
break;
case MouseButtons.XButton2:
upFlag = MOUSEEVENTF_XUP;
mouseData = XBUTTON2;
break;
default:
continue;
}
mouse_event(upFlag, 0, 0, mouseData, 0);
}
heldMouseButtons.Clear();
}
private void RegisterGlobalHotkey()
{
UnregisterHotKey(this.Handle, HOTKEY_ID);
UnregisterHotKey(this.Handle, MOUSEMOVE_HOTKEY_ID);
if (Enum.TryParse(settings.ToggleAutomationAction, out Keys automationKey))
{
RegisterHotKey(this.Handle, HOTKEY_ID, 0, (uint)automationKey);
}
if (Enum.TryParse(settings.ToggleMouseMoveAction, out Keys mouseMoveKey))
{
RegisterHotKey(this.Handle, MOUSEMOVE_HOTKEY_ID, 0, (uint)mouseMoveKey);
}
}
private void UnregisterGlobalHotkey()
{
UnregisterHotKey(this.Handle, HOTKEY_ID);
UnregisterHotKey(this.Handle, MOUSEMOVE_HOTKEY_ID);
}
private void ApplyDarkMode()
{
this.BackColor = Color.FromArgb(30, 30, 30);
this.ForeColor = Color.White;
foreach (Control control in this.Controls)
{
if (control is NumericUpDown || control is Button)
{
control.BackColor = Color.FromArgb(45, 45, 45);
control.ForeColor = Color.White;
}
}
}
private void nudSkill1_ValueChanged(object sender, EventArgs e)
{
settings.Skill1Delay = (int)nudSkill1.Value;
MarkAsChanged();
SaveSettings();
}
private void nudSkill2_ValueChanged(object sender, EventArgs e)
{
settings.Skill2Delay = (int)nudSkill2.Value;
MarkAsChanged();
SaveSettings();
}
private void nudSkill3_ValueChanged(object sender, EventArgs e)
{
settings.Skill3Delay = (int)nudSkill3.Value;
MarkAsChanged();
SaveSettings();
}
private void nudSkill4_ValueChanged(object sender, EventArgs e)
{
settings.Skill4Delay = (int)nudSkill4.Value;
MarkAsChanged();
SaveSettings();
}
private void nudRightClick_ValueChanged(object sender, EventArgs e)
{
settings.PrimaryAttackDelay = (int)nudPrimaryAttack.Value;
MarkAsChanged();
SaveSettings();
}
private void nudLeftClick_ValueChanged(object sender, EventArgs e)
{
settings.SecondaryAttackDelay = (int)nudSecondaryAttack.Value;
MarkAsChanged();
SaveSettings();
}
private void nudPotion_ValueChanged(object sender, EventArgs e)
{
settings.PotionDelay = (int)nudPotion.Value;
MarkAsChanged();
SaveSettings();
}
private void nudMove_ValueChanged(object sender, EventArgs e)
{
settings.MoveDelay = (int)nudMove.Value;
MarkAsChanged();
SaveSettings();
}
private void nudDodge_ValueChanged(object sender, EventArgs e)
{
settings.DodgeDelay = (int)nudDodge.Value;
MarkAsChanged();
SaveSettings();
}
private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
{
if (!PromptSaveChanges())
{
e.Cancel = true; // Cancel the closing if user cancels save operation
return;
}
SaveSettings();
UnregisterGlobalHotkey();
ReleaseHeldInputs(); // Release any held inputs before closing
controllerCheckTimer?.Stop();
controllerCheckTimer?.Dispose();
moveTimer?.Dispose();
controller = null;
// Close and dispose overlay
if (overlayForm != null && !overlayForm.IsDisposed)
{
overlayForm.Close();
overlayForm.Dispose();
}
}
private void btnKeyConfig_Click(object sender, EventArgs e)
{
// Unregister hotkeys to prevent them from triggering during configuration
UnregisterGlobalHotkey();
using (var keyConfigForm = new KeyConfigForm(settings))
{
if (keyConfigForm.ShowDialog() == DialogResult.OK)
{
MarkAsChanged();
SaveSettings();
UpdateKeyMappings();
UpdateLabels();
}
}
// Re-register hotkeys after configuration dialog closes
RegisterGlobalHotkey();
}
private void btnHordesConfig_Click(object sender, EventArgs e)
{
using (var hordesConfigForm = new HordesConfigForm(settings, () =>
{
MarkAsChanged();
SaveSettings();
}))
{
hordesConfigForm.ShowDialog();
}
}
private void UpdateKeyMappings()
{
keyMappings = new Dictionary<string, Action>
{
{"Skill1", () => SimulateAction(settings.Skill1Action, settings.Skill1Delay == 1)},
{"Skill2", () => SimulateAction(settings.Skill2Action, settings.Skill2Delay == 1)},
{"Skill3", () => SimulateAction(settings.Skill3Action, settings.Skill3Delay == 1)},
{"Skill4", () => SimulateAction(settings.Skill4Action, settings.Skill4Delay == 1)},
{"PrimaryAttack", () => SimulateAction(settings.PrimaryAttackAction, settings.PrimaryAttackDelay == 1)},
{"SecondaryAttack", () => SimulateAction(settings.SecondaryAttackAction, settings.SecondaryAttackDelay == 1)},
{"Move", () => SimulateAction(settings.MoveAction, settings.MoveDelay == 1)},
{"Potion", () => SimulateAction(settings.PotionAction, settings.PotionDelay == 1)},
{"Dodge", () => SimulateAction(settings.DodgeAction, settings.DodgeDelay == 1)}
};
RegisterGlobalHotkey();
}
// Add this field to the MainForm class
private Dictionary<string, Action> keyMappings;
private void SimulateAction(string action, bool holdAction = false)
{
switch (action)
{
case "LeftClick":
SimulateMouseClick(MouseButtons.Left, holdAction);
break;
case "RightClick":
SimulateMouseClick(MouseButtons.Right, holdAction);
break;
case "MiddleClick":
SimulateMouseClick(MouseButtons.Middle, holdAction);
break;
case "MouseBack":
SimulateMouseClick(MouseButtons.XButton1, holdAction);
break;
case "MouseForward":
SimulateMouseClick(MouseButtons.XButton2, holdAction);
break;
default:
if (Enum.TryParse(action, out Keys key))
{
SimulateKeyPress(key, holdAction);
}
break;
}
}
private string SerializeSettingsToJson(Settings settings)
{
var json = new StringBuilder();
json.AppendLine("{");
json.AppendLine($" \"Skill1Delay\": {settings.Skill1Delay},");
json.AppendLine($" \"Skill2Delay\": {settings.Skill2Delay},");
json.AppendLine($" \"Skill3Delay\": {settings.Skill3Delay},");
json.AppendLine($" \"Skill4Delay\": {settings.Skill4Delay},");
json.AppendLine($" \"PrimaryAttackDelay\": {settings.PrimaryAttackDelay},");
json.AppendLine($" \"SecondaryAttackDelay\": {settings.SecondaryAttackDelay},");
json.AppendLine($" \"MoveDelay\": {settings.MoveDelay},");
json.AppendLine($" \"PotionDelay\": {settings.PotionDelay},");
json.AppendLine($" \"DodgeDelay\": {settings.DodgeDelay},");
json.AppendLine($" \"Skill1Action\": \"{EscapeJsonString(settings.Skill1Action)}\",");
json.AppendLine($" \"Skill2Action\": \"{EscapeJsonString(settings.Skill2Action)}\",");
json.AppendLine($" \"Skill3Action\": \"{EscapeJsonString(settings.Skill3Action)}\",");
json.AppendLine($" \"Skill4Action\": \"{EscapeJsonString(settings.Skill4Action)}\",");
json.AppendLine($" \"PrimaryAttackAction\": \"{EscapeJsonString(settings.PrimaryAttackAction)}\",");
json.AppendLine($" \"SecondaryAttackAction\": \"{EscapeJsonString(settings.SecondaryAttackAction)}\",");
json.AppendLine($" \"MoveAction\": \"{EscapeJsonString(settings.MoveAction)}\",");
json.AppendLine($" \"PotionAction\": \"{EscapeJsonString(settings.PotionAction)}\",");
json.AppendLine($" \"DodgeAction\": \"{EscapeJsonString(settings.DodgeAction)}\",");
json.AppendLine($" \"ToggleAutomationAction\": \"{EscapeJsonString(settings.ToggleAutomationAction)}\",");
json.AppendLine($" \"ToggleMouseMoveAction\": \"{EscapeJsonString(settings.ToggleMouseMoveAction)}\",");
json.AppendLine($" \"LastLoadedConfigFile\": \"{EscapeJsonString(settings.LastLoadedConfigFile)}\"");
json.AppendLine("}");
return json.ToString();
}
private string EscapeJsonString(string value)
{
if (string.IsNullOrEmpty(value)) return "";
return value.Replace("\\", "\\\\").Replace("\"", "\\\"");
}
private Settings DeserializeSettingsFromJson(string json)
{
var settings = new Settings();
// Simple JSON parsing - split by lines and extract key-value pairs
var lines = json.Split('\n');
foreach (var line in lines)
{
var trimmed = line.Trim().TrimEnd(',');
if (trimmed.Contains(":"))
{
var parts = trimmed.Split(new[] { ':' }, 2);
if (parts.Length == 2)
{
var key = parts[0].Trim().Trim('"');
var value = parts[1].Trim().Trim('"');