VC 實現文件與應用程序關聯


      日常工作中,doc文件直接雙擊后,就能啟動word軟件,並讀取該文檔的內容在軟件中顯示,這都得益於注冊表的配置,我們的軟件也需要實現這樣的功能,該如何寫注冊表以及寫入哪些內容呢?下面的兩個函數就能實現這個功能。CheckFileRelation是檢查注冊表中是否已經將我們期待的文件格式與相應軟件關聯了;RegisterFileRelation是直接往注冊表中寫入相關的key和value。

/****************************************************
* 檢測文件關聯情況
* 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);
}

有了這兩個函數后,可以實現文檔和軟件的關聯了,但是雙擊文檔后,又是如何讀取文檔的內容的呢?這里主要是用到了命令行參數,我們需要在CTestApp的InitInstance函數獲取命令行參數,如:

BOOL CTestApp::InitInstance()
{
    //這里的m_lpCmdLine是CWinApp的成員變量,雙擊文檔時,文檔的路徑會傳給該參數
    CString pathName = m_lpCmdLine;
    if (pathName != _T(""))
    {
      //TODO:讀取文件、解析文件、呈現文件
} }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM