我想将“.abc”文件关联到我的 WPF 应用程序。
我使用以下代码添加关联:
public class FileAssociation
{
static RegistryKey Root
{
get
{
return Registry.CurrentUser;
}
}
// Associate file extension with progID, description, icon and application
public static void Associate(string extension,
string progID, string description, string application)
{
Require.NotNullOrEmpty(extension, "extension");
Require.NotNullOrEmpty(progID, "progID");
Require.NotNullOrEmpty(application, "application");
Require.NotNullOrEmpty(description, "description");
Root.CreateSubKey(extension).SetValue("", progID);
using (var key = Root.CreateSubKey(progID))
{
key.SetValue("", description);
key.CreateSubKey("DefaultIcon").SetValue("", ToShortPathName(application).Quote() + ",0");
key.CreateSubKey(@"Shell\Open\Command").SetValue("", ToShortPathName(application).Quote() + " \"%1\"");
// Tell explorer the file association has been changed
SHChangeNotify(0x08000000, 0x0000, IntPtr.Zero, IntPtr.Zero);
}
}
// Return true if extension already associated in registry
public static bool IsAssociated(string extension)
{
return (Root.OpenSubKey(extension, false) != null);
}
[DllImport("shell32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern void SHChangeNotify(uint wEventId, uint uFlags, IntPtr dwItem1, IntPtr dwItem2);
[DllImport("Kernel32.dll")]
private static extern uint GetShortPathName(string lpszLongPath,
[Out] StringBuilder lpszShortPath, uint cchBuffer);
// Return short path format of a file name
private static string ToShortPathName(string longName)
{
StringBuilder s = new StringBuilder(1000);
uint iSize = (uint)s.Capacity;
uint iRet = GetShortPathName(longName, s, iSize);
return s.ToString();
}
}
注意: Quote() 扩展方法仅用于将字符串 abc 转换为“abc”。
现在文件关联工作正常!我可以双击“.abc”文件来打开我的 WPF 应用程序。
但是 DefaultIcon 不起作用。DefaultIcon 注册键设置为"D:\path\to\MyWPFApp.exe",0
。我的 WPF 应用程序的应用程序图标设置为属性页面中的图标(我可以看到 MyWPFApp.exe 的图标已更改)。怎么了?谢谢!
顺便说一句:我在 Windows 8 中使用 .NET 4