C#のWPFで外字を表示する その2

タイトル

前回↓

Windowsでの外字ファイルの仕組みを踏まえて、WPFで外字を表示するにはレジストリから外字ファイルのパスを取得し、そのパスで明示的にフォントファミリへ外字を追加するコードを書き加える必要がある。

システム全体で外字を利用するには以下のようなコードになる。
こちらも参照↓




フォントファミリに外字を追加


    public partial class App : Application
    {
        public App()
        {
            var ffDef  = Window.FontFamilyProperty.DefaultMetadata.DefaultValue as System.Windows.Media.FontFamily;
            var ffName = ffDef.Source;

            string eudc    = "C:\\Windows\\Fonts\\EUDC.tte";
            string eudcDef = null;
            string eudcCur = null;
            using (RegistryKey key = Registry.CurrentUser.OpenSubKey("EUDC\\932"))
            {
                foreach (var nm in key.GetValueNames())
                {
                    if (0 == nm.CompareTo("SystemDefaultEUDCFont"))
                        eudcDef = key.GetValue(nm) as string;

                    if (0 == nm.CompareTo(ffName))
                        eudcCur = key.GetValue(nm) as string;
                }
                if (null != eudcDef) eudc = eudcDef;
                if (null != eudcCur) eudc = eudcCur;
            }

            ffName = ffName + ", file:///" + eudc.Replace('\\', '/') + "#EUDC";
            var font = new System.Windows.Media.FontFamily(ffName);

            var style = new Style(typeof(Window));
            style.Setters.Add(new Setter(Window.FontFamilyProperty, font));

            FrameworkElement.StyleProperty.OverrideMetadata(typeof(Window), new FrameworkPropertyMetadata(style));
        }
    }

デフォルトのフォントファミリ名を取得 (5~6行目)

メイリオとか固定の名前でもいいけど、OSのバージョンによってデフォルトのフォントが違ったりするので一応それに合わせる。
WindowクラスのFontFamilyプロパティからデフォルトの値を取得している。

レジストリから外字ファイルのフルパスを取得 (8~23行目)

レジストリの[HKEY_CURRENT_USER\EUDC\932\]を開き「SystemDefaultEUDCFont」と使用するフォントの外字パスを取得する。
使用するフォントと一致する値があればそれを使う。
それ以外の場合は「SystemDefaultEUDCFont」の値を使う。

取得した外字ファイル名からフォントファミリを作成 (25~26行目)

外字ファイル名を成形してフォントファミリ名にする。

WindowクラスのStyleプロパティをオーバーライド (28~31行目)

WindowクラスをTargetTypeとしたStyleを作成。
作成したFontFamilyオブジェクトをFontFamilyPropertyへセットする。
作成したStyleオブジェクトでFrameworkPropertyMetadataオブジェクトを作成。
FrameworkElement.StyleProperty.OverrideMetadataメソッドでWindowクラスのStyleプロパティをオーバーライドする。 




コメント