注册表修改文件关联(默认程序)

Introduction

由于各种原因(主要是安全方面考虑),Windows中修改文件关联的Api一改再改,改了又改。

而直接修改注册表+刷新Explorer的方法,也许是比较方便的能兼容各个Windows版本(NT6+)的方案(也许需要管理员权限)。

Code

[-HKEY_CURRENT_USER\Software\Classes\{{AppName}}.{{Extension}}]

[HKEY_CURRENT_USER\Software\Classes\{{AppName}}.{{Extension}}]

[HKEY_CURRENT_USER\Software\Classes\{{AppName}}.{{Extension}}\DefaultIcon]
@="{{IconFile}},{{IconIndex}}"

[HKEY_CURRENT_USER\Software\Classes\{{AppName}}.{{Extension}}\shell]

[HKEY_CURRENT_USER\Software\Classes\{{AppName}}.{{Extension}}\shell\open]

[HKEY_CURRENT_USER\Software\Classes\{{AppName}}.{{Extension}}\shell\open\command]
@="\"{{AppPath}}\" \"%1\""

[HKEY_CURRENT_USER\Software\Classes\.{{Extension}}]
@="{{AppName}}.{{Extension}}"

[HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\FileExts\.{{Extension}}]
"Progid"="{{AppName}}.{{Extension}}"

[HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\FileExts\.{{Extension}}\OpenWithProgids]
"{{AppName}}.{{Extension}}"=hex(0):

[HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\FileExts\.{{Extension}}\UserChoice]
"Progid"="{{AppName}}.{{Extension}}"

示例:用Nodejs生成注册表文件

let fs = require('fs');

let templetStr = fs.readFileSync(`${__dirname}/templet.reg`).toString();
let extensionArr = 'avi wmv wmp wm asf mpg mpeg mpe m1v m2v'.split(' ');
let appName = 'PotPlayerMini'
let appPath = 'C:\\\\Program Files\\\\PotPlayer\\\\PotPlayerMini.exe' // Need 4 '\\'
let outputText = '';
for (let extension of extensionArr) {
    outputText += generateReg(appPath, appName, extension, appPath, '0');
}
fs.writeFileSync(`${__dirname}/output_${Date.now()}.reg`, outputText);

function generateReg(appPath, appName, extension, iconFile, iconIndex) {
    let outputStr = templetStr;
    outputStr = outputStr.replace(/{{AppPath}}/g, appPath);
    outputStr = outputStr.replace(/{{AppName}}/g, appName);
    outputStr = outputStr.replace(/{{Extension}}/g, extension);
    outputStr = outputStr.replace(/{{IconFile}}/g, iconFile);
    outputStr = outputStr.replace(/{{IconIndex}}/g, iconIndex);
    return outputStr;
}