WPF应用程序文件关联:DefaultIcon不工作
本文关键字:DefaultIcon 工作 关联 应用程序 文件 WPF | 更新日期: 2023-09-27 18:11:58
我要关联"。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的图标已经更改)。怎么了?谢谢!
顺便说一句:我用。net 4在Windows 8
您不需要DefaultIcon
条目。默认情况下使用第一个图标。
移除它,它应该可以工作^^
如果我删除ToShortPathName
(长名称可以用引号)和更改Root
属性returns Registry.ClassesRoot
代码在这里工作。