[Toy code] Use C++ to get the PID corresponding to the form process

A pop-up window pops up on the desktop inexplicably, and you can't just turn it off. You have to know which process is responsible for it.

Write a small piece of code in C++ (Windows API) to get the handle of the window where the mouse is located, and then get the corresponding PID. The code is very simple and will not be explained.

#include <Windows.h>
#include <iostream>
#include <cstdio>
using namespace std;

POINT lastCursorPos;
POINT CursorPos;
HWND hWnd;
char line[100] = "\0";
int len = 0;

DWORD GetPIDFromCursor(POINT &CursorPos)
{
    
    
    //从鼠标位置获取当前窗体的句柄
    hWnd = WindowFromPoint(CursorPos);
    if (NULL == hWnd)
    {
    
    
        // cout << "\nNo window exists at the given point!" << endl;
        return 0;
    }

    //获取窗体句柄的pid
    DWORD dwProcId;
    GetWindowThreadProcessId(hWnd, &dwProcId);
    return dwProcId;
}


bool equal(const POINT &p1, const POINT &p2)
{
    
    
    if (p1.x == p2.x && p1.y == p2.y)
        return true;
    else
        return false;
}

void ClearLine()
{
    
    
    strset(line, ' ');
    printf("\r%s\r", line);
}

int main()
{
    
    
    bool go = true;
    int pid;
    while (go)
    {
    
    
        GetCursorPos(&CursorPos);
        if (!equal(CursorPos, lastCursorPos))
        {
    
    
            pid = GetPIDFromCursor(CursorPos);
            //动态更新一行的内容
            ClearLine();
            sprintf(line, "Position=(%d, %d), PID = %d", CursorPos.x, CursorPos.y, pid);
            cout << line;
            lastCursorPos = CursorPos;
        }
    }
    // CloseWindow(hWnd);
    return 0;
}

Compile and run the program.

The effect is as follows:
insert image description here

Guess you like

Origin blog.csdn.net/frostime/article/details/114294326