-
-
Notifications
You must be signed in to change notification settings - Fork 38
/
Copy pathMain.c
523 lines (471 loc) · 14.4 KB
/
Main.c
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
// Main.c
// UniversalPauseButton
// Joseph Ryan Ries, 2015-2023
// ryanries09@gmail.com
// https://github.com/ryanries/UniversalPauseButton/
#ifndef UNICODE
#define UNICODE
#endif
#ifndef _UNICODE
#define _UNICODE
#endif
#define WM_TRAYICON (WM_USER + 1)
#include <Windows.h>
#include <stdio.h>
#include <TlHelp32.h>
#include "Main.h"
#include "resource.h"
CONFIG gConfig;
HANDLE gDbgConsole = INVALID_HANDLE_VALUE;
BOOL gIsRunning = TRUE;
HANDLE gMutex;
NOTIFYICONDATA gTrayNotifyIconData;
BOOL gIsPaused;
u32 gPreviouslyPausedProcessId;
int WINAPI wWinMain(_In_ HINSTANCE Instance, _In_opt_ HINSTANCE PrevInstance, _In_ PWSTR CmdLine, _In_ int CmdShow)
{
UNREFERENCED_PARAMETER(PrevInstance);
UNREFERENCED_PARAMETER(CmdLine);
UNREFERENCED_PARAMETER(CmdShow);
HMODULE NtDll = NULL;
MSG WndMsg = { 0 };
//HHOOK KeyboardHook = NULL;
if (LoadRegistrySettings() != ERROR_SUCCESS)
{
goto Exit;
}
gMutex = CreateMutexW(NULL, FALSE, APPNAME);
if (GetLastError() == ERROR_ALREADY_EXISTS)
{
MsgBox(L"An instance of the program is already running.", APPNAME L" Error", MB_OK | MB_ICONERROR);
goto Exit;
}
if ((NtDll = GetModuleHandleW(L"ntdll.dll")) == NULL)
{
MsgBox(L"Unable to locate ntdll.dll!\nError: 0x%08lx", APPNAME L" Error", MB_OK | MB_ICONERROR, GetLastError());
goto Exit;
}
if ((NtSuspendProcess = (_NtSuspendProcess)((void*)GetProcAddress(NtDll, "NtSuspendProcess"))) == NULL)
{
MsgBox(L"Unable to locate the NtSuspendProcess procedure in the ntdll.dll module!", APPNAME L" Error", MB_OK | MB_ICONERROR);
goto Exit;
}
if ((NtResumeProcess = (_NtResumeProcess)((void*)GetProcAddress(NtDll, "NtResumeProcess"))) == NULL)
{
MsgBox(L"Unable to locate the NtResumeProcess procedure in the ntdll.dll module!", APPNAME L" Error", MB_OK | MB_ICONERROR);
goto Exit;
}
// There will be no visible window either way, but in one case, there will be a system tray icon,
// and in the other case there will be no icon. This is because someone requested that I make this
// app work even when the user has no shell (explorer.exe) or has replaced their shell with an alternative shell.
// The Windows system tray API obviously won't work if there is no Windows system tray. I don't know if the user's
// shell even has a taskbar so I'm skipping that too.
if (gConfig.TrayIcon)
{
WNDCLASSW WndClass = { 0 };
HWND HWnd = NULL;
WndClass.hInstance = Instance;
WndClass.lpszClassName = APPNAME L"_WndClass";
WndClass.lpfnWndProc = SysTrayCallback;
if (RegisterClassW(&WndClass) == 0)
{
MsgBox(L"Failed to register WindowClass! Error 0x%08lx", APPNAME L" Error", MB_OK | MB_ICONERROR, GetLastError());
goto Exit;
}
HWnd = CreateWindowExW(
WS_EX_TOOLWINDOW,
WndClass.lpszClassName,
APPNAME L"_Systray_Window",
WS_ICONIC,
CW_USEDEFAULT,
CW_USEDEFAULT,
CW_USEDEFAULT,
CW_USEDEFAULT,
0,
0,
Instance,
0);
if (HWnd == NULL)
{
MsgBox(L"Failed to create window! Error 0x%08lx", APPNAME L" Error", MB_OK | MB_ICONERROR, GetLastError());
goto Exit;
}
gTrayNotifyIconData.cbSize = sizeof(NOTIFYICONDATA);
gTrayNotifyIconData.hWnd = HWnd;
gTrayNotifyIconData.uID = 1982;
gTrayNotifyIconData.uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP;
gTrayNotifyIconData.uCallbackMessage = WM_TRAYICON;
wcscpy_s(gTrayNotifyIconData.szTip, _countof(gTrayNotifyIconData.szTip), APPNAME L" v" VERSION);
gTrayNotifyIconData.hIcon = (HICON)LoadImageW(GetModuleHandleW(NULL), MAKEINTRESOURCEW(IDI_ICON1), IMAGE_ICON, 0, 0, 0);
if (gTrayNotifyIconData.hIcon == NULL)
{
MsgBox(L"Failed to load systray icon resource!", APPNAME L" Error", MB_OK | MB_ICONERROR);
goto Exit;
}
if (Shell_NotifyIconW(NIM_ADD, &gTrayNotifyIconData) == FALSE)
{
MsgBox(L"Failed to register systray icon!", APPNAME L" Error", MB_OK | MB_ICONERROR);
goto Exit;
}
}
if (RegisterHotKey(NULL, 1, MOD_NOREPEAT, gConfig.PauseKey) == 0)
{
MsgBox(L"Failed to register hotkey! Error 0x%08lx", APPNAME L" Error", MB_OK | MB_ICONERROR, GetLastError());
goto Exit;
}
DbgPrint(L"Registered hotkey 0x%x.", gConfig.PauseKey);
while (gIsRunning)
{
while (PeekMessageW(&WndMsg, NULL, 0, 0, PM_REMOVE))
{
if (WndMsg.message == WM_HOTKEY)
{
HandlePauseKeyPress();
}
DispatchMessageW(&WndMsg);
}
Sleep(5);
}
Exit:
return(0);
}
void HandlePauseKeyPress(void)
{
HANDLE ProcessHandle = NULL;
HANDLE ProcessSnapshot = NULL;
PROCESSENTRY32W ProcessEntry = { sizeof(PROCESSENTRY32W) };
u32 ProcessId = 0;
// Either we configured it to pause/un-pause a specified process, or we will pause/un-pause
// the currently in-focus foreground window.
if (wcslen(gConfig.ProcessNameToPause) > 0)
{
if (gIsPaused)
{
// Process currently paused, need to un-pause it.
UnpausePreviouslyPausedProcess();
}
else
{
// Process needs to be paused.
DbgPrint(L"Pause key pressed. Attempting to pause named process %s...", gConfig.ProcessNameToPause);
ProcessSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (ProcessSnapshot == INVALID_HANDLE_VALUE)
{
MsgBox(L"Failed to create snapshot of running processes! Error 0x%08lx", APPNAME L" Error", MB_OK | MB_ICONERROR, GetLastError());
goto Exit;
}
if (Process32FirstW(ProcessSnapshot, &ProcessEntry) == FALSE)
{
MsgBox(L"Failed to retrieve list of running processes! Error 0x%08lx", APPNAME L" Error", MB_OK | MB_ICONERROR, GetLastError());
goto Exit;
}
do
{
if (_wcsicmp(ProcessEntry.szExeFile, gConfig.ProcessNameToPause) == 0)
{
ProcessId = ProcessEntry.th32ProcessID;
DbgPrint(L"Found process %s with PID %d.", ProcessEntry.szExeFile, ProcessId);
break;
}
} while (Process32NextW(ProcessSnapshot, &ProcessEntry));
if (ProcessId == 0)
{
DbgPrint(L"Unable to locate any process with the name %s!", gConfig.ProcessNameToPause);
goto Exit;
}
ProcessHandle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, ProcessId);
if (ProcessHandle == NULL)
{
MsgBox(L"Failed to open process %d! Error 0x%08lx", APPNAME L" Error", MB_OK | MB_ICONERROR, ProcessId, GetLastError());
goto Exit;
}
NtSuspendProcess(ProcessHandle);
gIsPaused = TRUE;
gPreviouslyPausedProcessId = ProcessId;
DbgPrint(L"Process paused!");
}
}
else
{
if (gIsPaused)
{
// Process currently paused, need to un-pause it.
UnpausePreviouslyPausedProcess();
}
else
{
// Process needs to be paused.
DbgPrint(L"Pause key pressed. Attempting to pause current foreground window...");
HWND ForegroundWindow = GetForegroundWindow();
if (ForegroundWindow == NULL)
{
MsgBox(L"Failed to detect foreground window!", APPNAME L" Error", MB_OK | MB_ICONERROR);
goto Exit;
}
GetWindowThreadProcessId(ForegroundWindow, &ProcessId);
if (ProcessId == 0)
{
MsgBox(L"Failed to get PID from foreground window! Error code 0x%08lx", APPNAME L" Error", MB_OK | MB_ICONERROR, GetLastError());
goto Exit;
}
ProcessHandle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, ProcessId);
if (ProcessHandle == NULL)
{
MsgBox(L"Failed to open process %d! Error 0x%08lx", APPNAME L" Error", MB_OK | MB_ICONERROR, ProcessId, GetLastError());
goto Exit;
}
NtSuspendProcess(ProcessHandle);
gIsPaused = TRUE;
gPreviouslyPausedProcessId = ProcessId;
DbgPrint(L"Process paused!");
}
}
Exit:
if (ProcessSnapshot && ProcessSnapshot != INVALID_HANDLE_VALUE)
{
CloseHandle(ProcessSnapshot);
}
if (ProcessHandle)
{
CloseHandle(ProcessHandle);
}
}
void UnpausePreviouslyPausedProcess(void)
{
HANDLE ProcessHandle = NULL;
DbgPrint(L"Pause key pressed. Attempting to un-pause previously paused PID %d.", gPreviouslyPausedProcessId);
ProcessHandle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, gPreviouslyPausedProcessId);
if (ProcessHandle == NULL)
{
// Maybe the previously paused process was killed, no longer exists?
MsgBox(L"Failed to open process %d! Error 0x%08lx", APPNAME L" Error", MB_OK | MB_ICONERROR, gPreviouslyPausedProcessId, GetLastError());
}
else
{
NtResumeProcess(ProcessHandle);
DbgPrint(L"Un-pause successful.");
}
gIsPaused = FALSE;
gPreviouslyPausedProcessId = 0;
if (ProcessHandle)
{
CloseHandle(ProcessHandle);
}
}
u32 LoadRegistrySettings(void)
{
u32 Result = ERROR_SUCCESS;
HKEY RegKey = NULL;
typedef struct _REG_SETTING
{
wchar_t* Name;
u32 DataType;
void* DefaultValue;
void* MinValue;
void* MaxValue;
void* Destination;
} REG_SETTING;
REG_SETTING Settings[] = {
{ // Debug should always be the first setting loaded.
.Name = L"Debug",
.DataType = REG_DWORD,
.DefaultValue = &(u32) { 0 },
.MinValue = &(u32) { 0 },
.MaxValue = &(u32) { 1 },
.Destination = &gConfig.Debug
},
{
.Name = L"TrayIcon",
.DataType = REG_DWORD,
.DefaultValue = &(u32) { 1 },
.MinValue = &(u32) { 0 },
.MaxValue = &(u32) { 1 },
.Destination = &gConfig.TrayIcon
},
{
.Name = L"PauseKey",
.DataType = REG_DWORD,
.DefaultValue = &(u32) { VK_PAUSE },
.MinValue = &(u32) { 1 },
.MaxValue = &(u32) { 0xFE },
.Destination = &gConfig.PauseKey
},
{
.Name = L"ProcessNameToPause",
.DataType = REG_SZ,
.DefaultValue = &(wchar_t[128]) { L"" },
.MinValue = NULL,
.MaxValue = NULL,
.Destination = &gConfig.ProcessNameToPause
}
};
Result = RegCreateKeyExW(HKEY_CURRENT_USER, L"SOFTWARE\\" APPNAME, 0, NULL, 0, KEY_ALL_ACCESS, NULL, &RegKey, NULL);
if (Result != ERROR_SUCCESS)
{
MsgBox(L"Failed to load registry settings!\nError: 0x%08lx", L"Error", MB_OK | MB_ICONERROR, Result);
goto Exit;
}
for (u32 s = 0; s < _countof(Settings); s++)
{
switch (Settings[s].DataType)
{
case REG_DWORD:
{
u32 BytesRead = sizeof(u32);
Result = RegGetValueW(
RegKey,
NULL,
Settings[s].Name,
RRF_RT_DWORD,
NULL,
Settings[s].Destination,
&BytesRead);
if (Result != ERROR_SUCCESS)
{
if (Result == ERROR_FILE_NOT_FOUND)
{
Result = ERROR_SUCCESS;
*(u32*)Settings[s].Destination = *(u32*)Settings[s].DefaultValue;
}
else
{
MsgBox(L"Failed to load registry value '%s'!\nError: 0x%08lx", L"Error", MB_OK | MB_ICONERROR, Settings[s].Name, Result);
goto Exit;
}
}
else
{
if (*(u32*)Settings[s].Destination < *(u32*)Settings[s].MinValue || *(u32*)Settings[s].Destination > *(u32*)Settings[s].MaxValue)
{
MsgBox(L"Registry value '%s' was out of range! Using default of %d.", L"Error", MB_OK | MB_ICONWARNING, Settings[s].Name, *(u32*)Settings[s].DefaultValue);
*(u32*)Settings[s].Destination = *(u32*)Settings[s].DefaultValue;
}
}
// Enable the debug console as early as possible if configured.
// This is so the debug console can report on the other registry settings.
if (Settings[s].Destination == &gConfig.Debug)
{
if (gConfig.Debug)
{
if (AllocConsole() == FALSE)
{
MsgBox(L"Failed to allocate debug console!\nError: 0x%08lx", L"Error", MB_OK | MB_ICONERROR, GetLastError());
goto Exit;
}
gDbgConsole = GetStdHandle(STD_OUTPUT_HANDLE);
if (gDbgConsole == INVALID_HANDLE_VALUE)
{
MsgBox(L"Failed to get stdout debug console handle!\nError: 0x%08lx", L"Error", MB_OK | MB_ICONERROR, GetLastError());
goto Exit;
}
DbgPrint(L"%s version %s.", APPNAME, VERSION);
DbgPrint(L"To disable this debug console, delete the 'Debug' reg setting at HKCU\\SOFTWARE\\%s", APPNAME);
}
}
DbgPrint(L"Using value 0n%d (0x%x) for registry setting '%s'.", *(u32*)Settings[s].Destination, *(u32*)Settings[s].Destination, Settings[s].Name);
break;
}
case REG_SZ:
{
u32 BytesRead = 128 * sizeof(wchar_t);
Result = RegGetValueW(
RegKey,
NULL,
Settings[s].Name,
RRF_RT_REG_SZ,
NULL,
Settings[s].Destination,
&BytesRead);
if (Result != ERROR_SUCCESS)
{
if (Result == ERROR_FILE_NOT_FOUND)
{
Result = ERROR_SUCCESS;
}
else
{
MsgBox(L"Failed to load registry value '%s'!\nError: 0x%08lx", L"Error", MB_OK | MB_ICONERROR, Settings[s].Name, Result);
goto Exit;
}
}
DbgPrint(L"Using value '%s' for registry setting '%s'.", Settings[s].Destination, Settings[s].Name);
break;
}
default:
{
MsgBox(L"Registry value '%s' was not of the expected data type!", L"Error", MB_OK | MB_ICONERROR, Settings[s].Name);
goto Exit;
}
}
}
Exit:
if (RegKey != NULL)
{
RegCloseKey(RegKey);
}
return(Result);
}
void MsgBox(const wchar_t* Message, const wchar_t* Caption, u32 Flags, ...)
{
wchar_t FormattedMessage[1024] = { 0 };
va_list Args = NULL;
va_start(Args, Flags);
_vsnwprintf_s(FormattedMessage, _countof(FormattedMessage), _TRUNCATE, Message, Args);
va_end(Args);
DbgPrint(FormattedMessage);
MessageBoxW(NULL, FormattedMessage, Caption, Flags);
}
void DbgPrint(const wchar_t* Message, ...)
{
if (gConfig.Debug == FALSE || gDbgConsole == INVALID_HANDLE_VALUE)
{
return;
}
wchar_t FormattedMessage[1024] = { 0 };
u32 MsgLen = 0;
wchar_t TimeString[64] = { 0 };
SYSTEMTIME Time;
va_list Args = NULL;
va_start(Args, Message);
_vsnwprintf_s(FormattedMessage, _countof(FormattedMessage), _TRUNCATE, Message, Args);
va_end(Args);
MsgLen = (u32)wcslen(FormattedMessage);
FormattedMessage[MsgLen] = '\n';
FormattedMessage[MsgLen + 1] = '\0';
GetLocalTime(&Time);
_snwprintf_s(TimeString, _countof(TimeString), _TRUNCATE, L"[%02d.%02d.%04d %02d.%02d.%02d.%03d] ", Time.wMonth, Time.wDay, Time.wYear, Time.wHour, Time.wMinute, Time.wSecond, Time.wMilliseconds);
WriteConsoleW(gDbgConsole, TimeString, (u32)wcslen(TimeString), NULL, NULL);
WriteConsoleW(gDbgConsole, FormattedMessage, (u32)wcslen(FormattedMessage), NULL, NULL);
}
LRESULT CALLBACK SysTrayCallback(_In_ HWND Window, _In_ UINT Message, _In_ WPARAM WParam, _In_ LPARAM LParam)
{
LRESULT Result = 0;
static BOOL QuitMessageBoxIsShowing = FALSE;
switch (Message)
{
case WM_TRAYICON:
{
if (!QuitMessageBoxIsShowing && (LParam == WM_LBUTTONDOWN || LParam == WM_RBUTTONDOWN || LParam == WM_MBUTTONDOWN))
{
QuitMessageBoxIsShowing = TRUE;
if (MessageBox(Window, L"Quit " APPNAME L"?", L"Are you sure?", MB_YESNO | MB_ICONQUESTION | MB_SYSTEMMODAL) == IDYES)
{
Shell_NotifyIconW(NIM_DELETE, &gTrayNotifyIconData);
gIsRunning = FALSE;
PostQuitMessage(0);
}
else
{
QuitMessageBoxIsShowing = FALSE;
}
}
break;
}
default:
{
Result = DefWindowProcW(Window, Message, WParam, LParam);
break;
}
}
return(Result);
}