实现效果
修改注册表, 将特定后缀名的文件和应用程序关联,当打开该后缀名对应的文件时会启动对应的应用程序
运行效果
关键代码
=============main.cpp====================
#include "mainwidget.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWidget w;
w.show();
for(int i=0; i<argc; i++)
{
w.appendText(argv[i]);
}
if(argc==2)
{
w.openFile(argv[1]);
}
return a.exec();
}
=============mainwidget.cpp================
#include "mainwidget.h"
#include "ui_mainwidget.h"
#include <QFile>
#include <QTextStream>
#include <QSettings>
#include <QDebug>
MainWidget::MainWidget(QWidget *parent) :
QWidget(parent),
ui(new Ui::MainWidget)
{
ui->setupUi(this);
ui->textEdit->setLineWrapMode(QTextEdit::NoWrap);
ui->textOut->setLineWrapMode(QTextEdit::NoWrap);
this->setWindowTitle("Tegistry Test");
}
MainWidget::~MainWidget()
{
delete ui;
}
void MainWidget::openFile(const QString &filePath)
{
ui->textOut->append(QString("openFile filePath=")+filePath);
QFile file(filePath);
if(file.open(QFile::ReadOnly | QFile::Text))
{
QTextStream ts(&file);
ui->textEdit->setText(ts.readAll());
file.close();
}
}
void MainWidget::appendText(const QString &text)
{
ui->textOut->append(text);
}
void MainWidget::on_buttonWrite_clicked()
{
QSettings settings("HKEY_CLASSES_ROOT\\.water", QSettings::NativeFormat);
settings.setValue(".", "waterpro");
QSettings settings2("HKEY_CLASSES_ROOT\\waterpro\\shell\\open\\command", QSettings::NativeFormat);
settings2.setValue(".", "\""+QApplication::applicationFilePath().replace("/", "\\")+"\" \"%1\"");
//注意,读写注册表时不需要调用sync函数
appendText("on_buttonWrite_clicked default="+settings2.value(".").toString());
appendText("Setted!");
}
void MainWidget::on_buttonRemove_clicked()
{
QSettings settings("HKEY_CLASSES_ROOT\\.water", QSettings::NativeFormat);
settings.clear();
QSettings settings2("HKEY_CLASSES_ROOT\\waterpro", QSettings::NativeFormat);
settings2.clear();
//注意,读写注册表时不需要调用sync函数
appendText("Removed!");
}
(4)参考资料