2
我想關聯「.abc」文件到我的WPF應用程序。WPF應用程序文件關聯:DefaultIcon不起作用
我添加使用此代碼的關聯:
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();
}
}
注:報價()擴展方法只是用來做字符串ABC爲 「ABC」。
現在文件關聯正常工作!我可以雙擊「.abc」文件來打開我的WPF應用程序。
但DefaultIcon不起作用。 DefaultIcon註冊表項設置爲"D:\path\to\MyWPFApp.exe",0
。我的WPF應用程序的應用程序圖標設置爲屬性頁面中的圖標(我可以看到MyWPFApp.exe的圖標已更改)。怎麼了?謝謝!
BTW:我使用.NET 4.0在Windows 8
謝謝。後來我找到了答案,但忘了在這裏更新它。你是對的,問題是Root屬性的返回值。在我的情況下,它應該是HKEY_CURRENT_USER /軟件/類,而不是HKEY_CURRENT_USER:p – 2013-05-24 13:30:23