安装字体

字体的安装需要调用到系统的api

 

        [DllImport("kernel32.dll", SetLastError = true)]
        static extern int WriteProfileString(string lpszSection, string lpszKeyName, string lpszString);
 
        [DllImport("user32.dll")]
        public static extern int SendMessage(int hWnd,uint msg,int wParam, int lParam);

        [DllImport("gdi32")]
        public static extern int AddFontResource(string lpFileName);

 

        public static bool installFont(FileInfo fontFileInfo)
        {
            try
            {
                Console.Write("installing font {0}", fontFileInfo.Name);
                string fontFileName = fontFileInfo.Name;
                string fontName = fontFileInfo.Name.Substring(0,
                    fontFileInfo.Name.LastIndexOf(".", StringComparison.Ordinal)); //获取字体名称

                const int wmFontchange = 0x001D;
                const int hwndBroadcast = 0xffff;


                string fontPath = string.Format(@"{0}\fonts\{1}",Environment.GetEnvironmentVariable("windir"),fontFileName ) ;


                if (!File.Exists(fontPath))
                {
                    File.Copy(fontFileInfo.FullName, fontPath); //将字体文件拷贝至系统目录
                    AddFontResource(fontPath); //************************
                    SendMessage(hwndBroadcast, wmFontchange, 0, 0);//************************
                    WriteProfileString("fonts", fontName + "(TrueType)", fontFileName);//************************
                    return true;
                }
            }
            catch (Exception exception)
            {
                Console.WriteLine("Error {0}",exception.Message);
            }

            return true;
        }

 

posted @ 2014-04-04 11:22  Alf7  阅读(275)  评论(0编辑  收藏  举报