本文實例講述了VC++實現添加文件關聯的方法。分享給大家供大家參考,具體如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
|
// 檢測文件關聯情況 // strExt: 要檢測的擴展名(例如: ".txt") // strAppKey: ExeName擴展名在注冊表中的鍵值(例如: "txtfile") // 返回TRUE: 表示已關聯,FALSE: 表示未關聯 BOOL CheckFileRelation( const char *strExt, const char *strAppKey) { int nRet=FALSE; HKEY hExtKey; char szPath[_MAX_PATH]; DWORD dwSize= sizeof (szPath); if (RegOpenKey(HKEY_CLASSES_ROOT,strExt,&hExtKey)==ERROR_SUCCESS) { RegQueryValueEx(hExtKey,NULL,NULL,NULL,( LPBYTE )szPath,&dwSize); if (_stricmp(szPath,strAppKey)==0) { nRet=TRUE; } RegCloseKey(hExtKey); return nRet; } return nRet; } //--------------------------------------------------------------------------- // 注冊文件關聯 // strExe: 要檢測的擴展名(例如: ".txt") // strAppName: 要關聯的應用程序名(例如: "C:\MyApp\MyApp.exe") // strAppKey: ExeName擴展名在注冊表中的鍵值(例如: "txtfile") // strDefaultIcon: 擴展名為strAppName的圖標文件(例如: "C:\MyApp\MyApp.exe,0") // strDescribe: 文件類型描述 void RegisterFileRelation( char *strExt, char *strAppName, char *strAppKey, char *strDefaultIcon, char *strDescribe) { char strTemp[_MAX_PATH]; HKEY hKey; RegCreateKey(HKEY_CLASSES_ROOT,strExt,&hKey); RegSetValue(hKey, "" ,REG_SZ,strAppKey, strlen (strAppKey)+1); RegCloseKey(hKey); RegCreateKey(HKEY_CLASSES_ROOT,strAppKey,&hKey); RegSetValue(hKey, "" ,REG_SZ,strDescribe, strlen (strDescribe)+1); RegCloseKey(hKey); sprintf (strTemp, "%s\\DefaultIcon" ,strAppKey); RegCreateKey(HKEY_CLASSES_ROOT,strTemp,&hKey); RegSetValue(hKey, "" ,REG_SZ,strDefaultIcon, strlen (strDefaultIcon)+1); RegCloseKey(hKey); sprintf (strTemp, "%s\\Shell" ,strAppKey); RegCreateKey(HKEY_CLASSES_ROOT,strTemp,&hKey); RegSetValue(hKey, "" ,REG_SZ, "Open" , strlen ( "Open" )+1); RegCloseKey(hKey); sprintf (strTemp, "%s\\Shell\\Open\\Command" ,strAppKey); RegCreateKey(HKEY_CLASSES_ROOT,strTemp,&hKey); sprintf (strTemp, "%s \"%%1\"" ,strAppName); RegSetValue(hKey, "" ,REG_SZ,strTemp, strlen (strTemp)+1); RegCloseKey(hKey); } |
用法如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
void CguanlianDlg::OnBnClickedOk() { // TODO: 在此添加控件通知處理程序代碼 //使用這兩個函數進行關聯的示例代碼 char strExt[10] = ".zwcTxt" ; char strAppKey[30] = "Windows.zwcTxt.1.0" ; BOOL relationExists = CheckFileRelation(strExt, strAppKey); if (!relationExists) { char strAppName[MAX_PATH + 1] = "E:\\Desktop\\Temp\\GMTools.exe" ; char strDefaultIcon[MAX_PATH + 1] = "" ; char strDescribe[100] = "WellTest Interpretation Files" ; RegisterFileRelation(strExt, strAppName, strAppKey, strDefaultIcon, strDescribe); } } |
希望本文所述對大家VC++程序設計有所幫助。
原文鏈接:http://blog.csdn.net/zwc2xm/article/details/55254895