文件关联是指打开一种类型的文件的默认方式比如默认状态下文本文件txt是与记事本程序相关联的我们双击文本文件就能直接运行记事本程序来编辑它。文件的关联是通过注册表得以实现的本例就是利用API函数RegCreateKey和RegSetValue来对注册表进行修改从中可以看到这两个函数的用法。
-------------------------------------- 利用WinApi函数实现文件关联 -------------------------------------- 程序说明: 例中利用两个API函数RegCreateKey和 RegSetValue修改注册表中的相应键值 实现某一类型文件.log同一个应用程序 notepad.exe的关联. -------------------------------------- 说明&作为数据类型的标示而不是“与”运算符 &指Long长整型数据其范围从 -2,147,483,648 到 2,147,483,647。Long 的类型声明字符为和号 (&)。
当关联按钮被按下时读写注册表完成 .log 文件和 记事本Notepad 的关联 如果你对注册表的结构和使用不熟悉的话可以参看“电脑乐园”中的相关教程
Private Sub Command1_Click() If CmdPressed = True Then Exit Sub
Dim sKeyName As String 键的名称 Dim sKeyValue As String 键值 Dim ret& 返回错误信息的变量 Dim lphKey& 此变量用来保存创建的键的句柄
实际效果是在注册表的HKEY_CLASSES_ROOT下创建MyApp目录 sKeyName = "MyApp" *名为MyApp的键名 sKeyValue = "Logfiles" *把键值设为"Logfiles" 在HKEY_CLASSES_ROOT中创建名为sKeyName的键并返回句柄lphKey& ret& = RegCreateKey&(HKEY_CLASSES_ROOT, sKeyName, lphKey&) 向句柄lphKey&所指的位置写入键值sKeyValue ret& = RegSetValue&(lphKey&, "", REG_SZ, sKeyValue, 0&) 在注册表的HKEY_CLASSES_ROOT下创建另外一个目录 .log sKeyName = ".log" *名为.log的键名 sKeyValue = "MyApp" *把键值设为"MyApp"
ret& = RegCreateKey&(HKEY_CLASSES_ROOT, sKeyName, lphKey&) ret& = RegSetValue&(lphKey&, "", REG_SZ, sKeyValue, 0&)
为“MyApp”设置了一个命令行 sKeyName = "MyApp" *名为MyApp的键名 sKeyValue = "notepad.exe %1" *把键值设为"notepad.exe %1"如果你知道DOS下的.Bat文件的语法的话便知%1指的是要打开的文件 如果该键已经创建则RegCreateKey那么函数会打开现有的项 ret& = RegCreateKey&(HKEY_CLASSES_ROOT, sKeyName, lphKey&) 下面一句的实际效果是在MyApp键下建立shell\open\command目录并写入键值sKeyValue 说明:放在一个键的shell\open\command下的是打开某一类型文件的应用程序的名称 ret& = RegSetValue&(lphKey&, "shell\open\command", REG_SZ, sKeyValue, MAX_PATH)
Command1.Caption = "关联已经创建"
Command1.Enabled = False CmdPressed = True End Sub
Private Sub Form_Load() CmdPressed = False End Sub
以下是模块文件中的代码:
Declare Function RegCreateKey& Lib "advapi32.dll" Alias "RegCreateKeyA" (ByVal hKey&, ByVal lpszSubKey$, lphKey&)
【VB声明】
Private Declare Function RegCreateKey Lib "advapi32.dll" Alias "RegCreateKeyA" (ByVal hKey As Long, ByVal lpSubKey As String, phkResult As Long) As Long
用VB建立文件关联一 |