2013-05-03 33 views
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

回答

1

你不需要DefaultIcon條目。第一個圖標是默認使用的。
刪除它,它應該工作^^

如果我刪除ToShortPathName(長名稱都確定了引號), 變化Root財產returns Registry.ClassesRoot代碼工作在這裏。

+0

謝謝。後來我找到了答案,但忘了在這裏更新它。你是對的,問題是Root屬性的返回值。在我的情況下,它應該是HKEY_CURRENT_USER /軟件/類,而不是HKEY_CURRENT_USER:p – 2013-05-24 13:30:23

相關問題