網頁點擊連結啟動本地應用程式 (如 QQ 聊天、迅雷下載) 是常見需求。本文解析 tencent:// 協議原理,演示如何註冊自定義 URI Scheme 讓瀏覽器啟動任意 Win32/MFC/.NET 程式並傳遞參數。
Windows 允許應用程式註冊為 URL 協議處理器:
Windows Registry Editor Version 5.00
[HKEY_CLASSES_ROOT\Tencent]
@="TencentProtocol"
"URL Protocol"="D:\Program Files\Tencent\QQ\Timwp.exe"
[HKEY_CLASSES_ROOT\Tencent\DefaultIcon]
@="D:\Program Files\Tencent\QQ\Timwp.exe,1"
[HKEY_CLASSES_ROOT\Tencent\shell\open\command]
@="\"D:\Program Files\Tencent\QQ\Timwp.exe\" \"%1\""
HKEY_CLASSES_ROOT\Tencent:協議名稱URL Protocol:標記為 URL 協議 (值可空)shell\open\command:啟動命令,%1 會被完整 URI 取代瀏覽器遇到 tencent://... → 查註冊表 → 啟動 Timwp.exe "tencent://..." → 應用程式解析參數。
helloworld://register.reg)
Windows Registry Editor Version 5.00
[HKEY_CLASSES_ROOT\HelloWorld]
@="HelloWorld Protocol"
"URL Protocol"=""
[HKEY_CLASSES_ROOT\HelloWorld\DefaultIcon]
@="D:\Path\HelloWorld.exe,1"
[HKEY_CLASSES_ROOT\HelloWorld\shell\open\command]
@="\"D:\Path\HelloWorld.exe\" \"%1\""
BOOL CHelloWorldApp::InitInstance() {
CCommandLineInfo cmdInfo;
ParseCommandLine(cmdInfo); // 解析命令列參數
CHelloWorldDlg dlg;
dlg.SetDisplayInfo(cmdInfo.m_strFileName); // 傳遞完整 URI
m_pMainWnd = &dlg;
dlg.DoModal();
return FALSE;
}
void CHelloWorldDlg::SetDisplayInfo(CString& strInfo) {
m_strInfo = strInfo;
}
BOOL CHelloWorldDlg::OnInitDialog() {
CDialog::OnInitDialog();
// 解析 "helloworld://hello world/"
int pos = m_strInfo.Find("//"); // 找到協議分隔符
m_strInfo = m_strInfo.Mid(pos + 2); // 取參數部分
m_strInfo.Delete(m_strInfo.GetLength() - 1); // 移除尾部 '/'
m_edit_info.SetWindowText(m_strInfo); // 顯示到編輯框
return TRUE;
}
register.reg 匯入註冊表helloworld://hello world/ → 彈出對話框顯示「hello world」<a href="helloworld://hello world">...</a> → 點擊啟動程式| 項目 | 建議 |
|---|---|
| 協議名稱 | 小寫、無特殊字元、唯一 (如公司縮寫+功能) |
| 路徑含空格 | 註冊表命令必須雙層引號:"\"Path\With Spaces\App.exe\" \"%1\"" |
| 參數解析 | 完整 URI 傳入,自行解析 (移除 scheme://、URL Decode) |
| 單實例 | 啟動時檢查互斥體,若已運行則傳參數給現有實例 (WM_COPYDATA/管道/IPC) |
| 安全性 | 驗證參數來源、限制危險操作、避免任意命令注入 |
| 安裝程式 | 在安裝腳本中寫入註冊表 (Inno Setup/NSIS/WiX) |
// Program.cs
static class Program {
[STAThread]
static void Main(string[] args) {
if (args.Length > 0) {
string uri = args[0]; // 完整 URI
// 解析 uri...
}
Application.Run(new MainForm());
}
}
註冊表命令:"\"Path\App.exe\" \"%1\"" (同原理)。
自定義 URI Scheme 是瀏覽器啟動本地應用的標準機制:註冊表關聯協議 → 瀏覽器啟動可執行檔傳遞完整 URI → 應用程式解析參數執行業務邏輯。掌握此機制,可實現網頁與桌面應用無縫整合 (如一鍵登入、本地編輯、硬體設備控制等)。