#include <stdio.h>
#include <Windows.h>
#include <Psapi.h>
#include <conio.h>

int main() {
    int seq = 0;
    printf("Clipboard monitor!  By aubilenon.  Press a key to exit\n\n");
    while(!kbhit()) {
        Sleep(10);
        int next = GetClipboardSequenceNumber();
        if (next == seq) continue;
        bool funnyBusiness = false;
        int count = CountClipboardFormats();
        if (seq && seq + count + 1 != next) {
            printf("Funny business detected!\n");
        }
        seq = next;
        HWND owner = GetClipboardOwner();
        char buf[4096];
        char *culprit = "???";
        if (owner == NULL) {
            culprit = "unknown";
        } else {
            DWORD pid;
            if (!GetWindowThreadProcessId(owner, &pid)) {
                culprit = "error2";
            } else {
                HANDLE hproc = OpenProcess(PROCESS_QUERY_INFORMATION, false, pid);
                if (!hproc) {
                    culprit = "error3";
                } else  {
				    if (!GetProcessImageFileNameA(hproc, buf, sizeof(buf))) {
					    culprit = "error4";
				    }
				    else {
					    culprit = strrchr(buf, '\\');
					    if (culprit) {
						    culprit++;
					    }
					    else {
						    culprit = buf;
					    }
					    
                    }
                    CloseHandle(hproc);
                }
            }
        }
        
        printf("Clipboard contains %d formats.  Sequence number: %d  Owner: %s\n", seq, count, culprit);        
    }
    printf("Keypress detected. exiting\n");
    return 0;
}