【玩具代码】用C++获取窗体进程对应的PID

桌面上莫名其妙弹出来弹窗,光关掉可不行,还得知道是哪个进程搞的鬼。

用C++(Windows API)写一段小小的代码,获取鼠标所在位置窗口的句柄,进而得到对应的 PID,代码很简单,就不做解释了。

#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;
}

编译好运行程序。

效果如下:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/frostime/article/details/114294326