这段代码测试程序,实现功能动态获取窗口大小,获取鼠标按键消息,获取鼠标所在窗口的位置,大小,窗口句柄
实现原理:
具体解析如下:
GetCursorPos(&pNow) // 获取鼠标当前位置
hwndPointNow = WindowFromPoint(pNow); // 获取鼠标所在窗口的句柄
::GetWindowThreadProcessId(hwndPointNow, &dwProcessID);//获取窗口PID
GetWindowRect(hwndPointNow, &rect);//获取窗口位置
#define KEY_DOWN(VK_NONAME) ((GetAsyncKeyState(VK_NONAME) & 0x8000) ? 1:0) 获取键值
/************************************************************************************
* filename : main.cpp
* comment : The left mouse button, right pulley, message capture, access to the mouse window handle, window position.
* author : liangqidong <18088708700@163.com>
* History : create by liangqidong @ 2017/09/18
*************************************************************************************/
#include <windows.h>
#include <tlhelp32.h> //CreateToolhelp32Snapshot
#include <string>
#include <iostream>
using namespace std;
#define KEY_DOWN(VK_NONAME) ((GetAsyncKeyState(VK_NONAME) & 0x8000) ? 1:0) //必要的,我是背下来的
HWND GetWindowHandleByPID(DWORD dwProcessID)
{
HWND h = GetTopWindow(0);
while (h)
{
DWORD pid = 0;
DWORD dwTheardId = GetWindowThreadProcessId(h, &pid);
if (dwTheardId != 0)
{
if (pid == dwProcessID/*your process id*/)
{
// here h is the handle to the window
if (GetTopWindow(h))
{
return h;
}
// return h;
}
}
h = ::GetNextWindow(h, GW_HWNDNEXT);
}
return NULL;
}
int main()
{
HWND hwndNow = GetWindowHandleByPID(13956);
while (1)
{
POINT pNow = { 0, 0 };
if (GetCursorPos(&pNow)) // 获取鼠标当前位置
{
HWND hwndPointNow = NULL;
DWORD dwProcessID = 0;
RECT rect;
hwndPointNow = WindowFromPoint(pNow); // 获取鼠标所在窗口的句柄
::GetWindowThreadProcessId(hwndPointNow, &dwProcessID);
if (13956 == dwProcessID)
{
GetWindowRect(hwndPointNow, &rect);
std::cout << "窗口的句柄:" << (int)hwndNow<< std::endl; // 鼠标所在窗口的句柄
std::cout << "鼠标所在窗口的句柄:" << (int)hwndPointNow << "ID:" << dwProcessID << std::endl; // 鼠标所在窗口的句柄
std::cout << "鼠标所在窗口的top:" << rect.top << std::endl; // 鼠标所在窗口的句柄
std::cout << "鼠标所在窗口的bottom:" << rect.bottom << std::endl; // 鼠标所在窗口的句柄
std::cout << "鼠标所在窗口的left:" << rect.left << std::endl; // 鼠标所在窗口的句柄
std::cout << "鼠标所在窗口的right:" << rect.right << std::endl; // 鼠标所在窗口的句柄
std::cout << "鼠标所在窗口的宽:" << rect.right - rect.left << std::endl; // 鼠标所在窗口的句柄
std::cout << "鼠标所在窗口的高:" << rect.bottom - rect.top << std::endl; // 鼠标所在窗口的句柄
printf("鼠标左键是否按下:");
if (KEY_DOWN(MOUSE_MOVED))printf("是");
else printf("否");
printf("\n");
printf("鼠标右键是否按下:");
if (KEY_DOWN(MOUSE_EVENT))printf("是");
else printf("否");
printf("\n");
printf("鼠标滚轮键是否按下:");
if (KEY_DOWN(MOUSE_WHEELED))printf("是");
else printf("否");
printf("\n");
}
Sleep(1000);
system("cls");//清屏
}
}
return 0;
}
有什么缺点请大家指教
具体代码请参考git git@code.csdn.net:snippets/2580563.git 点击打开链接