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
| using System;
using Microsoft.Win32;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using ARTool;
namespace warhey
{
public interface IKeyDownEventHandler
{
bool Handle(KeyEventArgs e);
}
public interface IWarKeyControl
{
void Save(string name, IWarKeyModel model);
IWarKeyModel Load(string name);
}
public interface IWarKeyModel
{
string Name { get; }
bool DisplayEnemysHP { get; }
bool DisplayAlliesHP { get; }
IDictionary<int, int> KeyMappers { get; }
}
public interface IWarKeyModelRepository
{
void Create(string name, IWarKeyModel model);
void Update(string name, IWarKeyModel model);
void Delete(string name);
IWarKeyModel Read(string name);
}
public interface IWarKeyView
{
IWarKeyModel GetCurrent();
void Update(IWarKeyModel model);
}
//keyboard
public class Keyboard
{
private const int WM_KEYDOWN = 0x100; //Сообщение для прессы
private const int WM_KEYUP = 0x101; //Отпустить сообщение
private const int WM_SYSKEYDOWN = 0x104;
private const int WM_SYSKEYUP = 0x105;
private IKeyDownEventHandler handler;
public Keyboard(IKeyDownEventHandler handler)
{
this.handler = handler;
Start();//можете прочесть коды это не для хоткей? нет
}
private static IntPtr hKeyboardHook = IntPtr.Zero;
// Константы клавиатуры
public const int WH_KEYBOARD_LL = 13;
public delegate int HookProc(int nCode, Int32 wParam, IntPtr lParam);
// Объявите тип события перехвата клавиатуры
private HookProc KeyboardHookProcedure;
/// <summary>
/// Объявите маршалинг структуры типа клавиатуры хук
/// Declare the marshaling structure type of keyboard hook
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public class KeyboardHookStruct
{
public int vkCode; // Представляет код виртуальной клавиатуры от 1 до 254
public int scanCode; // Указывает код сканирования оборудования
public int flags;
public int time;
public int dwExtraInfo;
}
[DllImport("kernel32.dll")]
public static extern IntPtr GetModuleHandle(string lpModuleName);
// Монтажный крюк mounted
[DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
public static extern IntPtr SetWindowsHookEx(int idHook, HookProc lpfn, IntPtr hInstance, int threadId);
// Следующий крюк
[DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
public static extern int CallNextHookEx(IntPtr hhk, int nCode, Int32 wParam, IntPtr lParam);
// Удалить крючок
[DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
public static extern int UnhookWindowsHookEx(IntPtr hhk);
private int KeyboardHookProc(int nCode, Int32 wParam, IntPtr lParam)
{
if (nCode < 0)
return CallNextHookEx(hKeyboardHook, nCode, wParam, lParam);
KeyboardHookStruct MyKBHookStruct = (KeyboardHookStruct)Marshal.PtrToStructure(lParam, typeof(KeyboardHookStruct));
if (wParam == WM_KEYDOWN || wParam == WM_SYSKEYDOWN)
{
Keys keyData = (Keys)MyKBHookStruct.vkCode;
KeyEventArgs e = new KeyEventArgs(keyData);
if (handler.Handle(e) == false)
return 1;
}
return CallNextHookEx(hKeyboardHook, nCode, wParam, lParam);
}
public void Start()
{
if (hKeyboardHook == IntPtr.Zero)
{
KeyboardHookProcedure = new HookProc(KeyboardHookProc);
using (System.Diagnostics.Process curProcess = System.Diagnostics.Process.GetCurrentProcess())
using (System.Diagnostics.ProcessModule curModule = curProcess.MainModule)
hKeyboardHook = SetWindowsHookEx(WH_KEYBOARD_LL, KeyboardHookProcedure, GetModuleHandle(curModule.ModuleName), 0);
if (hKeyboardHook == IntPtr.Zero)
Stop();
}
}
public void Stop()
{
if (hKeyboardHook != IntPtr.Zero)
{
UnhookWindowsHookEx(hKeyboardHook);
hKeyboardHook = IntPtr.Zero;
}
}
// Разгрузить крюк в деструкторе
~Keyboard()
{
Stop();
}
}
//keyboarddecription
public static class KeyboardDescription
{
private static char[] Alphabet = new char[] { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' };
private static Dictionary<int, string> KeyToDescriptionDictionary = new Dictionary<int, string>();
private static Dictionary<string, int> DescriptionToKeyDictionary = new Dictionary<string, int>();
static KeyboardDescription()
{
InitializeKeyToDescriptionDictionary();
InitializeDescriptionToKeyDictionary();
}
private static void InitializeKeyToDescriptionDictionary()
{
//ROBIT
KeyToDescriptionDictionary.Add(13, "Enter");
KeyToDescriptionDictionary.Add(0x10, "Shift");
KeyToDescriptionDictionary.Add(0x11, "ctrl");
KeyToDescriptionDictionary.Add(9, "Tab");
KeyToDescriptionDictionary.Add(20, "CapsLock");
KeyToDescriptionDictionary.Add(32, "Space");
KeyToDescriptionDictionary.Add(112, "F1");
KeyToDescriptionDictionary.Add(113, "F2");
KeyToDescriptionDictionary.Add(114, "F3");
KeyToDescriptionDictionary.Add(115, "F4");
KeyToDescriptionDictionary.Add(192, "`");
// Буква A-Z
for (int i = 65; i <= 90; i++)
{
KeyToDescriptionDictionary.Add(i, Alphabet[i - 65].ToString());
}
// Алфавитные номера клавиатуры
for (int i = 48; i <= 57; i++)
KeyToDescriptionDictionary.Add(i, (i - 48).ToString());
// Область цифровой клавиатуры
for (int i = 96; i <= 105; i++)
KeyToDescriptionDictionary.Add(i, "D" + (i - 96));
}
private static void InitializeDescriptionToKeyDictionary()
{
foreach (var pair in KeyToDescriptionDictionary)
{
DescriptionToKeyDictionary.Add(pair.Value, pair.Key);
}
}
public static string GetDescription(int keyValue)
{
if (KeyToDescriptionDictionary.ContainsKey(keyValue))
return KeyToDescriptionDictionary[keyValue];
return ((char)keyValue).ToString();
}
public static int GetKey(string description)
{
if (DescriptionToKeyDictionary.ContainsKey(description))
return DescriptionToKeyDictionary[description];
return 0;
}
}
public class KeyTextBox : TextBox
{
public KeyTextBox()
{
this.TextAlign = HorizontalAlignment.Center;
this.Font = new System.Drawing.Font("Times New Roman", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
}
public int KeyValue
{
get
{
return KeyboardDescription.GetKey(this.Text);
}
set
{
this.Text = KeyboardDescription.GetDescription(value);
}
}
protected override bool IsInputKey(Keys keyData)
{
switch (keyData)
{
case Keys.Tab:
return true;
default:
return base.IsInputKey(keyData);
}
}
protected override void OnKeyUp(KeyEventArgs e)
{
if (e.KeyCode == Keys.Delete || e.KeyCode == Keys.Back)
{
this.Text = "";
}
else
{
this.Text = KeyboardDescription.GetDescription(e.KeyValue);
e.Handled = true;
}
base.OnKeyUp(e);
}
protected override void OnKeyPress(KeyPressEventArgs e)
{
e.Handled = true;
base.OnKeyPress(e);
}
}
public class WarKeyController : IWarKeyControl, IKeyDownEventHandler
{
private IWarKeyModel model;
private IWarKeyView view;
private IWarKeyModelRepository repository;
private Keyboard keyboard;
private frmMain frmMain;
public WarKeyController(IWarKeyView view)
{
this.view = view;
this.model = view.GetCurrent();
this.repository = new WarKeyModelRepository();
keyboard = new Keyboard(this);
}
public WarKeyController(frmMain frmMain)
{
this.frmMain = frmMain;
}
public void Save(string name, IWarKeyModel model)
{
this.model = model;
repository.Update(name, model);
}
public IWarKeyModel Load(string name)
{
IWarKeyModel model = repository.Read(name);
return model;
}
public bool Handle(KeyEventArgs e)
{
if (WarcraftWindow.IsForeground == false)
return true;
if (model.DisplayEnemysHP)
WarcraftWindow.DisplayEnemysHP();
if (model.DisplayAlliesHP)
WarcraftWindow.DisplayAlliesHP();
if (model.KeyMappers.ContainsKey(e.KeyValue))
{
WarcraftWindow.Send(model.KeyMappers[e.KeyValue]);
// Когда пространство сопоставлено и не находится в состоянии чата, экран WAR переносится на ближайшую военную точку.
if (e.KeyValue == 32 && WarcraftWindow.IsChating == false)
return false;
}
return true;
}
}
public class WarKeyModelRepository : IWarKeyModelRepository
{
public void Create(string name, IWarKeyModel model)
{
BinaryFormatter formatter = new BinaryFormatter();
MemoryStream stream = new MemoryStream();
formatter.Serialize(stream, model);
RegistryKey hklm = Registry.LocalMachine;
RegistryKey hkSoftware = hklm.OpenSubKey("Software", true);
RegistryKey hkWarKey = hkSoftware.CreateSubKey("WarKey");
hkWarKey.SetValue(name, stream.ToArray());
hkWarKey.Close();
}
public void Update(string name, IWarKeyModel model)
{
Create(name, model);
}
public void Delete(string name)
{
RegistryKey hklm = Registry.LocalMachine;
RegistryKey hkSoftware = hklm.OpenSubKey("Software", true);
RegistryKey hkWarKey = hkSoftware.CreateSubKey("WarKey");
hkWarKey.DeleteValue(name, false);
hkSoftware.Close();
}
public IWarKeyModel Read(string name)
{
IWarKeyModel model;
byte[] bytesSaved;
RegistryKey hklm = Registry.LocalMachine;
RegistryKey hkSoftware = hklm.OpenSubKey("Software", true);
RegistryKey hkWarKey = hkSoftware.CreateSubKey("WarKey");
if (hkWarKey.GetValue(name) == null)
bytesSaved = (byte[])hkWarKey.GetValue("default");
else
bytesSaved = (byte[])hkWarKey.GetValue(name);
BinaryFormatter formatter = new BinaryFormatter();
MemoryStream stream = new MemoryStream(bytesSaved);
model = (IWarKeyModel)formatter.Deserialize(stream);
return model;
}
}
public static class WarcraftWindow
{
private static readonly uint WM_KEYDOWN = 0x100;
private static readonly uint WM_KEYUP = 0x101;
private static readonly int KEY_QUOTLEFT = 219; // [
private static readonly int KEY_QUOTRIGHT = 221; // ]
// Используется для включения и отключения разрешения в токене доступа
private static readonly int TOKEN_ADJUST_PRIVILEGES = 0x20;
// Используется для запроса токена доступа
private static readonly int TOKEN_QUERY = 0x8;
// Флаг разрешения доступа
private static readonly int SE_PRIVILEGE_ENABLED = 0x2;
//private static readonly int PROCESS_ALL_ACCESS = 0x1F0FFF;
private static readonly int PROCESS_VM_READ = 0x0010;
private static readonly int PROCESS_VM_WRITE = 0x0020;
[DllImport("user32.dll")]
public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
[DllImport("user32.dll")]
public static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll")]
public static extern int SendMessage(IntPtr hWnd, uint Msg, int wParam, int lParam);
//[DllImport("user32.dll")]
//public static extern void keybd_event(Byte bVk, Byte bScan, Int32 dwFlags, Int32 dwExtraInfo);
//API необходимы для повышения
[DllImport("advapi32.dll", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
public static extern int OpenProcessToken(IntPtr ProcessHandle, int DesiredAccess, ref IntPtr TokenHandle);
[DllImport("advapi32.dll", EntryPoint = "LookupPrivilegeValueA", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
public static extern int LookupPrivilegeValue(string lpSystemName, string lpName, ref LUID lpLuid);
[DllImport("advapi32.dll", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
public static extern int AdjustTokenPrivileges(IntPtr TokenHandle, int DisableAllPrivileges, ref TOKEN_PRIVILEGES NewState, int BufferLength, ref TOKEN_PRIVILEGES PreviousState, ref int ReturnLength);
[DllImport("kernel32.dll")]
public static extern IntPtr OpenProcess(int dwDesiredAccess, bool bInheritHandle, int dwProcessId);
[DllImport("User32.dll", CharSet = CharSet.Auto)]
public static extern int GetWindowThreadProcessId(IntPtr hwnd, out int ID);
//Читать память
[DllImportAttribute("kernel32.dll", EntryPoint = "ReadProcessMemory")]
public static extern bool ReadProcessMemory(IntPtr hProcess, int lpBaseAddress, IntPtr lpBuffer, int nSize, IntPtr lpNumberOfBytesRead);
[DllImport("kernel32.dll")]
private static extern void CloseHandle(IntPtr hObject);
#region 提升权限所需的结构体
public struct LUID
{
// Младшие 32 бита локального уникального знака
public int LowPart;
// Верхние 32 бита местного уникального логотипа
public int HighPart;
}
public struct LUID_AND_ATTRIBUTES
{
public LUID pLuid;
// Атрибут LUID указан, и его значением может быть 32-битный флаг
public int Attributes;
}
public struct TOKEN_PRIVILEGES
{
// Содержит набор сведений о разрешениях для токена доступа: разрешения, которые имеет токен доступа
// Определяет емкость массива разрешений
public int PrivilegeCount;
// Укажите группу структур LUID_AND_ATTRIBUTES, каждая структура содержит атрибуты LUID и разрешения
public LUID_AND_ATTRIBUTES Privileges;
}
#endregion
/// <summary>
/// Существует ли окно Warcraft?
/// </summary>
public static bool Exisits
{
get { return FindWindow(null, "Warcraft III") != IntPtr.Zero; }
}
/// <summary>
/// Является ли окно Warcraft передним фокусом
/// </summary>
public static bool IsForeground
{
get
{
IntPtr war3 = FindWindow(null, "Warcraft III");
return war3 == GetForegroundWindow();
}
}
/// <summary>
/// В чате ли окно Warcraft?
/// </summary>
public static bool IsChating
{
get
{
// Считайте значение в адресе памяти, измененном во время состояния чата, открытый чат - 1, закрытый - 0, предустановка 0
int isChating = 0;
IntPtr tokenHandle = IntPtr.Zero;
LUID privilegeLUID = new LUID();
TOKEN_PRIVILEGES newPrivileges = new TOKEN_PRIVILEGES();
TOKEN_PRIVILEGES tokenPrivileges = default(TOKEN_PRIVILEGES);
OpenProcessToken(Process.GetCurrentProcess().Handle, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, ref tokenHandle);
LookupPrivilegeValue("", "SeDebugPrivilege", ref privilegeLUID);
tokenPrivileges.PrivilegeCount = 1;
tokenPrivileges.Privileges.Attributes = SE_PRIVILEGE_ENABLED;
tokenPrivileges.Privileges.pLuid = privilegeLUID;
int Size = 4;
IntPtr dota = FindWindow(null, "Warcraft III");
if ((AdjustTokenPrivileges(tokenHandle, 0, ref tokenPrivileges, 4 + (12 * tokenPrivileges.PrivilegeCount), ref newPrivileges, ref Size)) != 0)
{
int dotaID;
IntPtr dotaProcess;
GetWindowThreadProcessId(dota, out dotaID);
dotaProcess = OpenProcess(PROCESS_VM_READ | PROCESS_VM_WRITE, false, dotaID);
byte[] buffer = new byte[4];
IntPtr byteAddress = Marshal.UnsafeAddrOfPinnedArrayElement(buffer, 0); //Получить адрес буфера
ReadProcessMemory(dotaProcess, 0x6FAE8450, byteAddress, 4, IntPtr.Zero); //Считать значение в указанной памяти в буфер
CloseHandle(dotaProcess);
isChating = Marshal.ReadInt32(byteAddress);
}
return isChating == 1;
}
}
/// <summary>
/// Отправить ключ-значение (блок чата)
/// </summary>
/// <param name="keyValue"></param>
public static void Send(int keyValue)
{
IntPtr war3 = FindWindow(null, "Warcraft III");
if (war3 == IntPtr.Zero || IsChating)
return;
SendMessage(war3, WM_KEYDOWN, keyValue, 0); //это WInAPI и есть c++ если тебе интересна эта штука, то читай pinvoke сайт и там все есть как вызывать функцию, как передать перехватить и т.тд я этими делами не занимаюсь и интереса нет к этому, так что увы, рад бы помочь
SendMessage(war3, WM_KEYUP, keyValue, 0);
}
/// <summary>
/// Показать врага HP
/// </summary>
public static void DisplayEnemysHP()
{
IntPtr war3 = FindWindow(null, "Warcraft III");
if (war3 == IntPtr.Zero)
return;
SendMessage(war3, WM_KEYDOWN, KEY_QUOTRIGHT, 0);
}
/// <summary>
/// Покажи дружескую кровь
/// </summary>
public static void DisplayAlliesHP()
{
IntPtr war3 = FindWindow(null, "Warcraft III");
if (war3 == IntPtr.Zero)
return;
SendMessage(war3, WM_KEYDOWN, KEY_QUOTLEFT, 0);
}
}
[Serializable]
public class WarKeyModel : IWarKeyModel
{
private string name;
private bool displayEnemysHP;
private bool displayAlliesHP;
private IDictionary<int, int> keyMappers;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="name">Название проекта</param>
/// <param name="displayEnemysHP">Показать вражеские бары крови</param>
/// <param name="displayAlliesHP">Покажи дружескую кровь</param>
/// <param name="keyMappers">Раскладка клавиатуры</param>
public WarKeyModel(string name, bool displayEnemysHP, bool displayAlliesHP, IDictionary<int, int> keyMappers)
{
this.name = name;
this.displayEnemysHP = displayEnemysHP;
this.displayAlliesHP = displayAlliesHP;
this.keyMappers = keyMappers;
}
/// <summary>
/// Название проекта
/// </summary>
public string Name
{
get { return this.name; }
}
/// <summary>
/// Показать вражеские бары крови
/// </summary>
public bool DisplayEnemysHP
{
get { return this.displayEnemysHP; }
}
/// <summary>
/// Покажи дружескую кровь
/// </summary>
public bool DisplayAlliesHP
{
get { return this.displayAlliesHP; }
}
/// <summary>
/// Раскладка клавиатуры
/// </summary>
public IDictionary<int, int> KeyMappers
{
get { return this.keyMappers; }
}
}
} |