標籤:txt desc exe 實現 erro char 應用 cstring har
轉載:http://www.cnblogs.com/RascallySnake/archive/2013/03/01/2939102.html
日常工作中,doc檔案直接雙擊後,就能啟動word軟體,並讀取該文檔的內容在軟體中顯示,這都得益於註冊表的配置,我們的軟體也需要實現這樣的功能,該如何寫註冊表以及寫入哪些內容呢?下面的兩個函數就能實現這個功能。CheckFileRelation是檢查註冊表中是否已經將我們期待的檔案格式與相應軟體關聯了;RegisterFileRelation是直接往註冊表中寫入相關的key和value。
1 /**************************************************** 2 * 檢測檔案關聯情況 3 * strExt: 要檢測的副檔名(例如: ".txt") 4 * strAppKey: ExeName副檔名在註冊表中的索引值(例如: "txtfile") 5 * 返回TRUE: 表示已關聯,FALSE: 表示未關聯 6 7 ******************************************************/ 8 9 BOOL CheckFileRelation(const char *strExt, const char *strAppKey)10 {11 int nRet=FALSE;12 HKEY hExtKey;13 char szPath[_MAX_PATH]; 14 DWORD dwSize=sizeof(szPath); 15 if(RegOpenKey(HKEY_CLASSES_ROOT,strExt,&hExtKey)==ERROR_SUCCESS)16 {17 RegQueryValueEx(hExtKey,NULL,NULL,NULL,(LPBYTE)szPath,&dwSize);18 if(_stricmp(szPath,strAppKey)==0)19 {20 nRet=TRUE;21 }22 RegCloseKey(hExtKey);23 return nRet;24 }25 return nRet;26 }
1 /**************************************************** 2 3 * 註冊檔案關聯 4 * strExe: 要檢測的副檔名(例如: ".txt") 5 * strAppName: 要相關 App程式名(例如: "C:/MyApp/MyApp.exe") 6 * strAppKey: ExeName副檔名在註冊表中的索引值(例如: "txtfile") 7 * strDefaultIcon: 副檔名為strAppName的表徵圖檔案(例如: *"C:/MyApp/MyApp.exe,0") 8 * strDescribe: 檔案類型描述 9 10 ****************************************************/11 12 void RegisterFileRelation(char *strExt, char *strAppName, char *strAppKey, char *strDefaultIcon, char *strDescribe)13 {14 char strTemp[_MAX_PATH];15 HKEY hKey;16 17 RegCreateKey(HKEY_CLASSES_ROOT,strExt,&hKey);18 RegSetValue(hKey,"",REG_SZ,strAppKey,strlen(strAppKey)+1);19 RegCloseKey(hKey);20 21 RegCreateKey(HKEY_CLASSES_ROOT,strAppKey,&hKey);22 RegSetValue(hKey,"",REG_SZ,strDescribe,strlen(strDescribe)+1);23 RegCloseKey(hKey);24 25 sprintf(strTemp,"%s//DefaultIcon",strAppKey);26 RegCreateKey(HKEY_CLASSES_ROOT,strTemp,&hKey);27 RegSetValue(hKey,"",REG_SZ,strDefaultIcon,strlen(strDefaultIcon)+1);28 RegCloseKey(hKey);29 30 sprintf(strTemp,"%s//Shell",strAppKey);31 RegCreateKey(HKEY_CLASSES_ROOT,strTemp,&hKey);32 RegSetValue(hKey,"",REG_SZ,"Open",strlen("Open")+1);33 RegCloseKey(hKey);34 35 sprintf(strTemp,"%s//Shell//Open//Command",strAppKey);36 RegCreateKey(HKEY_CLASSES_ROOT,strTemp,&hKey);37 sprintf(strTemp,"%s /"%%1/"",strAppName);38 RegSetValue(hKey,"",REG_SZ,strTemp,strlen(strTemp)+1);39 RegCloseKey(hKey);40 }
有了這兩個函數後,可以實現文檔和軟體的關聯了,但是雙擊文檔後,又是如何讀取文檔的內容的呢?這裡主要是用到了命令列參數,我們需要在CTestApp的InitInstance函數擷取命令列參數,如:
1 BOOL CTestApp::InitInstance()2 {3 //這裡的m_lpCmdLine是CWinApp的成員變數,雙擊文檔時,文檔的路徑會傳給該參數4 CString pathName = m_lpCmdLine;5 if (pathName != _T(""))6 {7 //TODO:讀取檔案、解析檔案、呈現檔案8 }9 }
VC 實現檔案與應用程式關聯(轉載)