-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.cpp
84 lines (73 loc) · 2.12 KB
/
main.cpp
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
/*=====================================================================
Focus Monitor
-------------
Copyright Glare Technologies Limited 2015 -
Code by Nicholas Chapman, nick@indigorenderer.com
Is designed to be used to catch annoying programs that steal Window focus.
Polls every X ms to work out what Window has focus. Prints out the path to the executable if a different programs gets focus.
=====================================================================*/
#include "Windows.h"
#include <psapi.h> // For access to GetModuleFileNameEx
#include <iostream>
#include <string>
#ifdef _UNICODE
#define tcout wcout
#define tcerr wcerr
#else
#define tcout cout
#define tcerr cerr
#endif
int main()
{
std::wstring state;
while(1)
{
HWND focus_handle = GetForegroundWindow();
if(focus_handle)
{
DWORD process_id;
GetWindowThreadProcessId(focus_handle, &process_id);
// http://stackoverflow.com/questions/1933113/c-windows-how-to-get-process-path-from-its-pid
HANDLE processHandle = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, process_id);
if(processHandle != NULL)
{
TCHAR filename[MAX_PATH];
if(GetModuleFileNameEx(processHandle, NULL, filename, MAX_PATH) == 0)
{
if(state != L"Failed to get module filename")
{
std::tcout << "Failed to get module filename." << std::endl;
state = L"Failed to get module filename";
}
}
else
{
const std::wstring cur_path(filename);
if(cur_path != state)
{
std::tcout << "============== New program has foreground window ============\n" << filename << std::endl;
state = cur_path;
}
}
CloseHandle(processHandle);
}
else
{
if(state != L"Failed to open process")
{
std::tcout << "Failed to open process." << std::endl;
state = L"Failed to open process";
}
}
}
else
{
if(state != L"No foreground window")
{
std::tcout << "No foreground window." << std::endl;
state = L"No foreground window";
}
}
Sleep(50); // Sleep for 50 ms.
}
}