QT 进程间通信——剪切板

简述

剪贴板(Clipboard)是由操作系统维护的一块内存区域,这块内存区域不属于任何单独的进程,但是每一个进程又都可以访问这块内存区域,而实质上当在一个进程中复制数据时,就是将数据放到该内存区域中,而当在另一个进程中粘贴数据时,则是从该块内存区域中取出数据。

从剪切板的定义中我们可以看出,剪切板和共享内存差不多,都是在系统中使用一块公共的内存,只是共享内存的公共内存是我们自己申请创建的,剪切板是由操作系统维护的。剪切板可以用来实现进程间通信,只是通常我们只在广义上把它认为是进程间通信的一种。因为剪切板是一种非常松散的交换媒介,不像共享内存中,我们在一个进程访问共享内存时会设置锁防止其他程序在此时访问该内存,而在剪切板中是没有这种机制的。

 


效果

这两个程序,一个程序获取桌面的截图并把图片保存在剪切板中,另一个程序则一直读取剪切板中保存的图片,然后显示出来:

 


代码之路

获取桌面截图,放在剪切板端:

mainwindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QTimer>
#include <QScreen>
#include <QClipboard>

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();

private slots:
    void on_Btn_shotScreen_clicked();

    void shotScreen();

private:
    Ui::MainWindow *ui;

    QTimer *timer;
    QScreen *screen;
    QPixmap img;
};

#endif // MAINWINDOW_H

mainwindow.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_Btn_shotScreen_clicked()
{
    timer = new QTimer;
    connect(timer, SIGNAL(timeout()), this, SLOT(shotScreen()));
    timer->start(200);
}

void MainWindow::shotScreen()
{
    screen = QGuiApplication::primaryScreen();
    img = screen->grabWindow(0);
    ui->label->setPixmap(img.scaled(ui->label->size()));

    QClipboard *clipBoard = QApplication::clipboard();
    clipBoard->setPixmap(img);
}

从剪切板端获取图片显示:

mainwindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QTimer>
#include <QClipboard>

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();

private slots:
    void fetchPicture();

private:
    Ui::MainWindow *ui;
    QPixmap img;
    QTimer *timer;
    QClipboard *clipBoard;
};

#endif // MAINWINDOW_H

mainwindow.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    clipBoard = QApplication::clipboard();
    clipBoard->clear();

    timer = new QTimer;
    connect(timer, SIGNAL(timeout()), this, SLOT(fetchPicture()));
    timer->start(200);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::fetchPicture()
{
    img = clipBoard->pixmap();
    ui->label->setPixmap(img.scaled(ui->label->size()));
}

源代码百度云下载地址:https://pan.baidu.com/s/1LspC80Vz65vrk9Szux2W9w     提取码:yhev

 

  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值