您的位置:首页 > 其它

VC 实现文件与应用程序关联(转载)

2016-10-31 11:50 471 查看
转载: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: 要关联的应用程序名(例如: "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 }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: