Skip to content

Commit 0728566

Browse files
committed
Added duplicate process checking
1 parent 6609630 commit 0728566

File tree

2 files changed

+56
-0
lines changed

2 files changed

+56
-0
lines changed

ExplorerPosition/includewindows.h

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,3 +8,5 @@
88

99
#include <psapi.h>
1010
#pragma comment(lib, "psapi.lib")
11+
12+
#include <tlhelp32.h>

ExplorerPosition/main.cpp

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,15 @@ bool iequals(const std::string& a, const std::string& b)
5757
});
5858
}
5959

60+
bool iequals(const std::wstring& a, const std::wstring& b)
61+
{
62+
return std::equal(a.begin(), a.end(),
63+
b.begin(), b.end(),
64+
[](wchar_t a, wchar_t b) {
65+
return towlower(a) == towlower(b);
66+
});
67+
}
68+
6069
bool pointWithinRect(POINT point, RECT rect)
6170
{
6271
return point.x >= rect.left &&
@@ -252,8 +261,53 @@ void WinEventProc(
252261
dprintf("\n");
253262
}
254263

264+
bool IsDuplicateProcessRunning(const std::string processName, DWORD pid)
265+
{
266+
bool exists = false;
267+
268+
HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL);
269+
270+
PROCESSENTRY32 entry;
271+
entry.dwSize = sizeof(PROCESSENTRY32);
272+
273+
if (Process32First(snapshot, &entry))
274+
{
275+
while (Process32Next(snapshot, &entry))
276+
{
277+
// dprintf("Process : %s (pid %d)\n", entry.szExeFile, entry.th32ProcessID);
278+
if (iequals(entry.szExeFile, processName) && entry.th32ProcessID != pid)
279+
{
280+
exists = true;
281+
break;
282+
}
283+
}
284+
}
285+
286+
CloseHandle(snapshot);
287+
return exists;
288+
}
289+
290+
bool checkHasDuplicateProcess()
291+
{
292+
char currentProcessNameFull[MAX_PATH];
293+
GetModuleFileName(nullptr, currentProcessNameFull, MAX_PATH);
294+
295+
const char *last = strrchr(currentProcessNameFull, '\\');
296+
std::string currentProcessName(last != NULL ? last + 1 : currentProcessNameFull);
297+
298+
// dprintf("This exe: %s (pid %d)\n", currentProcessName.c_str(), GetCurrentProcessId());
299+
return IsDuplicateProcessRunning(currentProcessName, GetCurrentProcessId());
300+
}
301+
255302
int __stdcall wWinMain(HINSTANCE instance, HINSTANCE, LPWSTR cmdArgs, int windowShowCmd)
256303
{
304+
// Prevent duplicate instances of this software
305+
if (checkHasDuplicateProcess())
306+
{
307+
MessageBoxA(nullptr, "This program is already running.\n\nExisting process can be closed from Task Manager (open by pressing Ctrl+Shift+Esc).", "Duplicate process", MB_OK | MB_ICONERROR);
308+
return 0;
309+
}
310+
257311
HWINEVENTHOOK hook = SetWinEventHook(
258312
EVENT_OBJECT_SHOW,
259313
EVENT_OBJECT_SHOW,

0 commit comments

Comments
 (0)