Qt实现Spy++的获取鼠标指向的外部窗口句柄及窗口标题功能

一、前言

        最近想利用Qt实现类似Spy++的获取鼠标指向的外部窗口句柄及窗口标题功能。

        主要通过定时器定时刷新鼠标位置重新输出新的窗口句柄、窗口标题、窗口类名、窗口样式和窗口矩形。        

二、实现代码

       1、 widget.h

#pragma once

#include <QWidget>
#include <QDebug>
#include <windows.h>
#include <QTimer>
#include "ui_widget.h"

class widget: public QWidget
{
	Q_OBJECT

public:
	widget(QWidget *parent = nullptr);
	~widget();

private slots:
	void on_pushButton_getPointWindowName_clicked(bool checked);
	void slotTimeFindWindowName();

private:
	Ui::widgetClass ui;

	QTimer* m_timer;
};

2、widget.cpp

#include "widget.h"

widget::widget(QWidget *parent)
	: QWidget(parent)
{
	ui.setupUi(this);

	m_timer = new QTimer();
	connect(m_timer, &QTimer::timeout, this, &widget::slotTimeFindWindowName);
}

widget::~widget()
{}

void widget::on_pushButton_getPointWindowName_clicked(bool checked)
{
	if (checked) {
		this->setCursor(Qt::PointingHandCursor);
		if (m_timer->isActive())
			m_timer->stop();
		m_timer->start(500);
	}
	else {
		this->setCursor(Qt::ArrowCursor);
		m_timer->stop();
	}
}

void widget::slotTimeFindWindowName()
{	
    POINT ptCursor;
	GetCursorPos(&ptCursor);
	//获取窗口句柄
	HWND hWnd = WindowFromPoint(ptCursor);
	if (hWnd != 0) {
		//获取窗口标题
		TCHAR szTitle[MAX_PATH];
		GetWindowText(hWnd, szTitle, MAX_PATH);
		//获取窗口类名
		TCHAR szClass[MAX_PATH];
		GetClassName(hWnd, szClass, MAX_PATH);
		//获取窗口样式
		LONG style = GetWindowLong(hWnd, GWL_STYLE);
		//获取窗口矩形
		RECT rect;
		GetWindowRect(hWnd, &rect);
		QRect window_rect(rect.left, rect.top, rect.right, rect.bottom);

		QString windowsHwnd = QString("%1").arg((quintptr)hWnd, QT_POINTER_SIZE, 16, QLatin1Char('0'));
		QString windowsTitle = QString::fromWCharArray(szTitle);
		QString windowsClass = QString::fromWCharArray(szClass);
		QString windowsStyle = QString("%1").arg(style, QT_POINTER_SIZE, 16, QChar('0'));
		QString windowsRect = QString("(%1,%2)-(%3,%4) %5×%6")\
			.arg(window_rect.topLeft().x())\
			.arg(window_rect.topLeft().y())\
			.arg(window_rect.bottomRight().x())\
			.arg(window_rect.bottomRight().y())\
			.arg(window_rect.width())\
			.arg(window_rect.height());

    	ui.lineEdit_windowHwnd->setText(windowsHwnd);
		ui.lineEdit_windowTitle->setText(windowsTitle);
		ui.lineEdit_windowClass->setText(windowsClass);
		ui.lineEdit_windowStyle->setText(windowsStyle);
		ui.lineEdit_windowRect->setText(windowsRect);
	}
}

3.widget.ui

三、实现效果

         将鼠标移动到外部窗口上,即可获取该窗口标题。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

源客V

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值