<1>[QTCN] Color Picker

reference

<1>[QTCN] Color Picker

Function

  • desktop top
  • Get global mouse coordinates and color (Web value, RGB)
  • Added : Press the right mouse button to stop/start

accomplish

06GetColorValueTools.pro

LIBS += -luser32 -lAdvapi32

main.cpp

#include "getcolorvaluetools.h"
#pragma execution_character_set("utf-8")
#include <QApplication>
#include <QTextCodec>
#include <QDesktopWidget>
#include <QStyleFactory>

#include <QDebug>
#include <QApplication>
#include <windows.h>
#include <QFont>
bool isMouseButtonPress=false;
HHOOK g_hook;
// 使用 WinAPI 来捕捉全局鼠标事件中的鼠标右键按下事件
LRESULT CALLBACK MouseHookProc(int nCode, WPARAM wParam, LPARAM lParam)
{
    
    
    if (nCode >= 0 && wParam == WM_RBUTTONDOWN)  // 捕捉鼠标右键按下事件
    {
    
    
        isMouseButtonPress=!isMouseButtonPress;
        qDebug() << "Right mouse button pressed!按下鼠标右键!";
    }

    return CallNextHookEx(g_hook, nCode, wParam, lParam);
}


int main(int argc, char *argv[])
{
    
    
    QApplication a(argc, argv);

    /* SetWindowsHookEx 函数来安装一个低级鼠标钩子 (WH_MOUSE_LL),并将一个回调函数 MouseHookProc 绑定到此钩子上。
      在回调函数中,我们检查钩子的消息码是否为鼠标右键按下事件 (WM_RBUTTONDOWN),如果是,则输出相应的消息 */
    g_hook = SetWindowsHookEx(WH_MOUSE_LL, MouseHookProc, NULL, 0);

    // 设置全局字体大小
    QFont font;
    font.setPointSize(15);  // 设置字体大小
    qApp->setFont(font);

    GetColorValueTools w;
    w.show();

    return a.exec();
}

getcolorvaluetools.h


#ifndef GETCOLORVALUETOOLS_H
#define GETCOLORVALUETOOLS_H
#pragma execution_character_set("utf-8")
#include <QWidget>
#include <QDesktopWidget>
#include <QApplication>
#include <QLabel>
#include <QLineEdit>
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QTimer>
#include <QIcon>
#include <QMouseEvent>
#include <QDebug>
#include <QScreen>

class GetColorValueTools : public QWidget

{
    
    
    Q_OBJECT

public:
    GetColorValueTools(QWidget *parent = nullptr);
    ~GetColorValueTools();
    bool eventFilter(QObject *watched,QEvent *ev) override;
    void  initUI();
    QLabel *labWeb;
    QLabel *labRgb;
    QLabel *labXY;
    QLabel *labTip;
    QLabel *labColor;

    QLineEdit *txtWeb;
    QLineEdit *txtRgb;
    QLineEdit *txtXY;
public slots:
    void ShowColorValue();
};

#endif // GETCOLORVALUETOOLS_H

getcolorvaluetools.cpp


#include "getcolorvaluetools.h"

extern bool isMouseButtonPress;
GetColorValueTools::GetColorValueTools(QWidget *parent)
    : QWidget(parent)
{
    
    

    initUI();

    // 定时器更新
    QTimer *updateTimer = new QTimer(this);
    updateTimer->callOnTimeout(this,&GetColorValueTools::ShowColorValue);
    updateTimer->start(100);
}

GetColorValueTools::~GetColorValueTools()
{
    
    
}

bool GetColorValueTools::eventFilter(QObject *watched, QEvent *ev)
{
    
    
    QMouseEvent *mouseEv=static_cast<QMouseEvent*>(ev);
    if(ev->type()==QEvent::MouseButtonPress&& mouseEv->buttons()&Qt::MouseButton::RightButton)    // 事件为 鼠标按下
    {
    
    
        qDebug()<<"右键按下"<<isMouseButtonPress;
    }
    return QObject::eventFilter(watched, ev);
}

void GetColorValueTools::initUI()
{
    
    
    //窗体居中显示
    QDesktopWidget *desktop=QApplication::desktop();
    int width=desktop->width();
    int height=desktop->height();
    //设置窗口只有最小化和关闭按钮 +窗口将始终显示在其他窗口之上
    setWindowFlags(Qt::WindowMinimizeButtonHint|Qt::WindowCloseButtonHint|Qt::WindowStaysOnTopHint);
    this->move((width-this->width())/2,(height-this->height())/2);
    this->setFixedSize(this->width(),this->height());

    setWindowIcon(QIcon(":/1.ico"));
    setWindowTitle(tr("颜色拾取器"));

    labWeb=new QLabel("Web值:",this);
    labRgb=new QLabel("RGB值:",this);
    labXY=new QLabel("XY值:",this);
    labTip=new QLabel("按下鼠标右键停止/开启",this);
    labColor=new QLabel(this);

    txtWeb=new QLineEdit(this);
    txtRgb=new QLineEdit(this);
    txtXY=new QLineEdit(this);

    // 设置自动调整大小的属性
    labWeb->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Preferred);
    labRgb->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Preferred);
    labXY->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Preferred);
    labColor->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Preferred);
    txtWeb->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);
    txtRgb->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);
    txtXY->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);
    labTip->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);

    QHBoxLayout *hLayoutColor=new QHBoxLayout();
    hLayoutColor->addWidget(labColor);
    QHBoxLayout *hLayoutWeb=new QHBoxLayout();
    hLayoutWeb->addWidget(labWeb,1);
    hLayoutWeb->addWidget(txtWeb,2);
    QHBoxLayout *hLayoutRgb=new QHBoxLayout();
    hLayoutRgb->addWidget(labRgb,1);
    hLayoutRgb->addWidget(txtRgb,2);
    QHBoxLayout *hLayoutXY=new QHBoxLayout();
    hLayoutXY->addWidget(labXY,1);
    hLayoutXY->addWidget(txtXY,2);

    QVBoxLayout *vLayoutRight=new QVBoxLayout();
    vLayoutRight->addLayout(hLayoutWeb);
    vLayoutRight->addLayout(hLayoutRgb);
    vLayoutRight->addLayout(hLayoutXY);
    vLayoutRight->addWidget(labTip);

    QHBoxLayout *hLayout=new QHBoxLayout();
    hLayout->addLayout(hLayoutColor);
    hLayout->addLayout(vLayoutRight);

    hLayout->setStretchFactor(hLayoutColor,1);
    hLayout->setStretchFactor(vLayoutRight,1);

    this->setLayout(hLayout);

    this->installEventFilter(this);// 安装事件过滤器

}

void GetColorValueTools::ShowColorValue()
{
    
    
	QString text;
    if (isMouseButtonPress)
        text = "按下鼠标右键<span style=\"color:red;\">停止</span>/开启";
    else
        text = "按下鼠标右键停止/<span style=\"color:blue;\">开启</span>";
    labTip->setText(text);
    
    if(isMouseButtonPress)
        return;
    int x = QCursor::pos().x();
    int y = QCursor::pos().y();

    txtXY->setText(tr("X:%1  Y:%2").arg(x).arg(y));
    QString strDecimalValue,strHex;
    // 根据鼠标位置截取屏幕上的一个2x2像素区域的图像
    QScreen *screen = qApp->primaryScreen();  // 获取主屏幕的QScreen对象
    QPixmap pixmap = screen->grabWindow(qApp->desktop()->winId(), x, y, 2, 2);
    if (!pixmap.isNull())
    {
    
    
        QImage image = pixmap.toImage();
        if (!image.isNull())
        {
    
    
            if (image.valid(0, 0))  //验证图像中的像素 (0, 0) 是否有效,确保要获取(0, 0)的颜色值存在于图像中
            {
    
    
                QColor color = image.pixel(0, 0);//获取该图像中 (0,0) 像素的颜色
                int red=color.red();
                int green=color.green();
                int blue=color.blue();
                // 结果转换为一个两位的十六进制字符串,并且如果不足两位,则使用 '0' 来进行填充
                QString strRed=QString("%1").arg(red&0xFF,2,16,QLatin1Char('0'));
                QString strGreen=QString("%1").arg(green&0xFF,2,16,QLatin1Char('0'));
                QString strBlue=QString("%1").arg(blue&0xFF,2,16,QLatin1Char('0'));

                strDecimalValue = tr("%1, %2, %3").arg(red).arg(green).arg(blue);
                // toUpper()所有字符转换为大写形式
                strHex=tr("#%1%2%3").arg(strRed.toUpper()).arg(strGreen.toUpper()).arg(strBlue.toUpper());
            }
        }
    }

    QString str=tr("background-color: rgb(%1);").arg(strDecimalValue);
    labColor->setStyleSheet(str);
    txtRgb->setText(strDecimalValue);
    txtWeb->setText(strHex);
}

Effect

insert image description here
insert image description here

fuzzy knowledge points

  1. QString::arg()
QString QString::arg(int a, int fieldWidth, int base, QChar fillChar)
`a`:要插入的整数值。
`fieldWidth`:字段宽度,用于指定插入的值所占据的最小宽度。如果插入的值的长度小于 fieldWidth,则使用 fillChar 填充剩余的宽度,默认情况下使用空格字符填充。
`base`:进制基数,用于格式化插入的整数值。默认情况下使用十进制。
`fillChar`:填充字符,用于在插入的值的左侧填充空白处。默认情况下使用空格字符。
int red=255;
QString("%1").arg(red&0xFF,2,16,QLatin1Char('0'));
`red & 0xFF`:要插入到占位符中的值,即 red 变量的最低8位。
`2`:指定字段宽度为2,即插入的字符串占据的最小宽度为2。
`16`:指定插入的值以十六进制的形式进行格式化`输出``QLatin1Char('0')`:指定填充字符为 '0',如果插入的字符串宽度小于2,则在左侧用 '0' 填充。
  1. Capture the right mouse button press event in the windows global mouse event

SetWindowsHookEx function to install a low-level mouse hook ( WH_MOUSE_LL) and MouseHookProcbind a callback function to this hook.
In the callback function, we check whether the message code of the hook is the right mouse button press event ( WM_RBUTTONDOWN), and if so, output the corresponding message

#include <QApplication>
#include <windows.h>
HHOOK g_hook;
// 使用 WinAPI 来捕捉全局鼠标事件中的鼠标右键按下事件
LRESULT CALLBACK MouseHookProc(int nCode, WPARAM wParam, LPARAM lParam)
{
    
    
    if (nCode >= 0 && wParam == WM_RBUTTONDOWN)  // 捕捉鼠标右键按下事件
    {
    
    
        qDebug() << "Right mouse button pressed!按下鼠标右键!";
    }

    return CallNextHookEx(g_hook, nCode, wParam, lParam);
}

g_hook = SetWindowsHookEx(WH_MOUSE_LL, MouseHookProc, NULL, 0);
  1. Tell the compiler to interpret the characters in the source code file as UTF-8 encoding to solve the last garbled character in Chinese
#pragma execution_character_set("utf-8")

Guess you like

Origin blog.csdn.net/qq_47355554/article/details/131451295