註冊文件原理:
我知道當點擊一個html文件時,瀏覽器就會自動打開,或者是點擊一個doc文件,Word就會運行。有沒有想過當用戶點擊你自己定義文件類型時,你的程序就會自動啓動呢?其實想做到這點很簡單,只須對註冊表做點手腳就行了。每一個文件類型的信息被保存在註冊表中的 'HKEY_CLASSES_ROOT'下面。假設我們自定義的文件類型的後綴爲.xhg,文件名爲Test_File_Hype (中間不能有空格).
- 首先在HKEY_CLASSES_ROOT下創建 .hyp HKEY_CLASSES_ROOT\.xhg將[默認]鍵值改爲"Test_File_Hype"。
- 然後在HKEY_CLASSES_ROOT下添加主鍵 Test_File_HypeHKEY_CLASSES_ROOT\Test_File_Hype
- 按照下面的路徑添加新的主鍵 HKEY_CLASSES_ROOT\Test_File_Hype\Shell HKEY_CLASSES_ROOT\Test_File_Hype\Shell\Open HKEY_CLASSES_ROOT\Test_File_Hype\Shell\Open\Command 將下面的字符作爲Command的鍵值 your application path.exe %1 (例如 C:\WINDOWS\HYP\HYP.EXE %1) 或許你還想爲自己的文件類型加上同自己的執行文件一樣的圖標,很簡單,照下面的方法添加就行了。HKEY_CLASSES_ROOT\Test_File_Hype\DefaultIcon 輸入鍵值 you application path.EXE,0 後面的零表示文件的圖標同程序的主圖標一致,如果你的程序有很多圖標,換一換數字就可改變文件顯示的圖標了。
下面的例子在桌面的右鍵快捷菜單中或在Windows資源管理器的“新建”中添加自己的文件類型。假設添加的是擴展名爲“.cs”的文件,說明文件爲“cs files”,默認文件的打開方式採用Windows中的寫字板notepad.exe打開。
程序清單18-2:
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using Microsoft.Win32;
namespace RegistryDemo { public partial class fRegistry : Form { public fRegistry() { InitializeComponent(); }
private void btnAddFileType_Click(object sender, EventArgs e) { RegistryKey csFileKey = Registry.ClassesRoot.CreateSubKey(".xhg"); csFileKey.SetValue("", "xhg"); RegistryKey rkey = csFileKey.CreateSubKey("ShellNew"); rkey.SetValue("NullFile", ""); csFileKey.Close(); csFileKey = Registry.ClassesRoot.CreateSubKey("xhg"); csFileKey.SetValue("", "xhg file"); rkey.SetValue("", "c:\\windows\\notepad.exe,1"); rkey.Close(); rkey = csFileKey.CreateSubKey("shell\\open\\command"); rkey.SetValue("", "c:\\windows\\notepad.exe"); rkey.Close(); MessageBox.Show("修改成功!"); } } }