• C#根据字体名通过注册表获取该字体文件路径(win10)两种方法推荐第二种


    方法一:

    直接先上源码:

            private System.Collections.Generic.SortedDictionary<string, string> ReadFontInformation()
            {
                var dictionary = new System.Collections.Generic.SortedDictionary<string, string>();
    
               
                    Microsoft.Win32.RegistryKey localMachineKey = Microsoft.Win32.Registry.LocalMachine;
                    // 打开注册表  
                    Microsoft.Win32.RegistryKey localMachineKeySub = localMachineKey.OpenSubKey("SOFTWARE\Microsoft\Windows NT\CurrentVersion\Fonts", false);
    
                    //获取字体名  
                    string[] mynames = localMachineKeySub.GetValueNames();
    
                    foreach (string name in mynames)
                    {
                        //获取字体的文件名  
                        string myvalue = localMachineKeySub.GetValue(name).ToString();
    
                        if (myvalue.Substring(myvalue.Length - 4).ToUpper() == ".TTF" && myvalue.Substring(1, 2).ToUpper() != @":")
                        {
                            string val = name.Substring(0, name.Length - 11);
                            dictionary[val] = myvalue;
                        }
                    }
                localMachineKeySub.Close();
                return dictionary;
            }
    

     解决思路:

    1. 打开windows/fonts目录, 右键下图, 勾选字体文件名称, 发现其实字体文件名称和显示的名称是有区别的

    2. 然后去注册表中看看, win+r→regedit, 定位  LocalMachine \SOFTWARE\Microsoft\Windows NT\CurrentVersion\Fonts 可以看到, 对应的键值对

    3. 既然有思路了, 就开始操作注册表, 注意, 如果在win7以上的系统中, 将localMachineKey.OpenSubKey("",true)第二个参数设置为true, 在xp下没有问题, 在win7以上就会报以下错误:

    4. 解决此错误的方法是增加应用程序配置清单文件, 然后做下面的修改, 但是在运行的时候, 会提示要求用管理员权限(提权). 全部代码和清单文件内容如下:

    //[System.Security.Permissions.RegistryPermissionAttribute(System.Security.Permissions.SecurityAction.PermitOnly, Read = @"HKEY_LOCAL_MACHINESOFTWAREMicrosoftWindows NTCurrentVersionFonts")]// 约束代码仅可读注册表
            private System.Collections.Generic.SortedDictionary<string, string> ReadFontInformation()
            {
                var dictionary = new System.Collections.Generic.SortedDictionary<string, string>();
    
               
                    Microsoft.Win32.RegistryKey localMachineKey = Microsoft.Win32.Registry.LocalMachine;
                    // 打开注册表  
                    Microsoft.Win32.RegistryKey localMachineKeySub = localMachineKey.OpenSubKey("SOFTWARE\Microsoft\Windows NT\CurrentVersion\Fonts", false);
    
                    //获取字体名  
                    string[] mynames = localMachineKeySub.GetValueNames();
    
                    foreach (string name in mynames)
                    {
                        //获取字体的文件名  
                        string myvalue = localMachineKeySub.GetValue(name).ToString();
    
                        if (myvalue.Substring(myvalue.Length - 4).ToUpper() == ".TTF" && myvalue.Substring(1, 2).ToUpper() != @":")
                        {
                            string val = name.Substring(0, name.Length - 11);
                            dictionary[val] = myvalue;
                        }
                    }
                localMachineKeySub.Close();
                return dictionary;
            }
    

     清单文件:

    <?xml version="1.0" encoding="utf-8"?>
    <assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1">
      <assemblyIdentity version="1.0.0.0" name="MyApplication.app"/>
      <trustInfo xmlns="urn:schemas-microsoft-com:asm.v2">
        <security>
          <requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3">
            <!-- UAC 清单选项
                 如果想要更改 Windows 用户帐户控制级别,请使用
                 以下节点之一替换 requestedExecutionLevel 节点。n
            <requestedExecutionLevel  level="asInvoker" uiAccess="false" />
            <requestedExecutionLevel  level="requireAdministrator" uiAccess="false" />
            <requestedExecutionLevel  level="highestAvailable" uiAccess="false" />
    
                指定 requestedExecutionLevel 元素将禁用文件和注册表虚拟化。
                如果你的应用程序需要此虚拟化来实现向后兼容性,则删除此
                元素。
            -->
            <requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
          </requestedPrivileges>
        </security>
      </trustInfo>
    
      <compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1">
        <application>
          <!-- 设计此应用程序与其一起工作且已针对此应用程序进行测试的
               Windows 版本的列表。取消评论适当的元素,Windows 将
               自动选择最兼容的环境。 -->
    
          <!-- Windows Vista -->
          <!--<supportedOS Id="{e2011457-1546-43c5-a5fe-008deee3d3f0}" />-->
    
          <!-- Windows 7 -->
          <!--<supportedOS Id="{35138b9a-5d96-4fbd-8e2d-a2440225f93a}" />-->
    
          <!-- Windows 8 -->
          <!--<supportedOS Id="{4a2f28e3-53b9-4441-ba9c-d69d4a4a6e38}" />-->
    
          <!-- Windows 8.1 -->
          <!--<supportedOS Id="{1f676c76-80e1-4239-95bb-83d0f6d0da78}" />-->
    
          <!-- Windows 10 -->
          <!--<supportedOS Id="{8e0f7a12-bfb3-4fe8-b9a5-48fd50a15a9a}" />-->
    
        </application>
      </compatibility>
    
      <!-- 指示该应用程序可以感知 DPI 且 Windows 在 DPI 较高时将不会对其进行
           自动缩放。Windows Presentation Foundation (WPF)应用程序自动感知 DPI,无需
           选择加入。选择加入此设置的 Windows 窗体应用程序(目标设定为 .NET Framework 4.6 )还应
           在其 app.config 中将 "EnableWindowsFormsHighDpiAutoResizing" 设置设置为 "true"。-->
      <!--
      <application xmlns="urn:schemas-microsoft-com:asm.v3">
        <windowsSettings>
          <dpiAware xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings">true</dpiAware>
        </windowsSettings>
      </application>
      -->
    
      <!-- 启用 Windows 公共控件和对话框的主题(Windows XP 和更高版本) -->
      <!--
      <dependency>
        <dependentAssembly>
          <assemblyIdentity
              type="win32"
              name="Microsoft.Windows.Common-Controls"
              version="6.0.0.0"
              processorArchitecture="*"
              publicKeyToken="6595b64144ccf1df"
              language="*"
            />
        </dependentAssembly>
      </dependency>
      -->
    
    </assembly>
    

     方法二:直接拿对应的文件名:

    public  class FontNameFile
        {
            public static string getFontFileName(string fontname)
            {
                string folderFullName = System.Environment.GetEnvironmentVariable("windir") + "\fonts";
                DirectoryInfo TheFolder = new DirectoryInfo(folderFullName);
                foreach (FileInfo NextFile in TheFolder.GetFiles())
                {
                    if (NextFile.Exists)
                    {
                        if (fontname==getFontName(NextFile.FullName))
                        {
                         
                            return NextFile.Name;
                        }
                    }
                }
                return "";
            }
    
            private static string getFontName(string fontfilename)
            {
                PrivateFontCollection pfc = new PrivateFontCollection();
                //只要ttf和TTF, 其它的本项目不需要
                if (fontfilename.EndsWith(".ttf") || fontfilename.EndsWith(".TTF"))
                {
                    pfc.AddFontFile(fontfilename);
                }
                if (pfc.Families.Length > 0)
                {
                    return pfc.Families[0].Name;
                }
                return "";
            }
        }
    

     

  • 相关阅读:
    uvm设计分析——report
    report源码分析——report_handle和report_server和report_catcher
    report源码分析——宏的执行
    015-命令行下载安装brew
    011-多线程-基础-基于AbstractQueuedSynchronizer自定义同步组件
    010-多线程-JUC集合-Queue-ConcurrentLinkedQueue
    009-多线程-JUC集合-Queue-LinkedBlockingDeque
    008-多线程-JUC集合-Queue-LinkedBlockingQueue
    007-多线程-JUC集合-Queue-BlockingQueue接口以及ArrayBlockingQueue
    006-多线程-集合-Set-ConcurrentSkipListSet
  • 原文地址:https://www.cnblogs.com/wxylog/p/6871815.html
Copyright © 2020-2023  润新知