Exemplo n.º 1
0
        public void Dispose_MultipleTimes_Nop()
        {
            var fontCollection = new PrivateFontCollection();

            fontCollection.Dispose();
            fontCollection.Dispose();
        }
Exemplo n.º 2
0
 /// <summary>
 /// 更新GroupBoxFont
 /// </summary>
 private async void UpdateGroupBoxFont()
 {
     Log.WriteLog(Log.LogLevel.信息, "从注册表获取系统已安装字体");
     FontSortedDictionary = ReadFontInformation();
     Log.WriteLog(Log.LogLevel.信息, "加载字体");
     foreach (var fonts in FontSortedDictionary)
     {
         // 读取字体文件
         var pfc = new PrivateFontCollection();
         pfc.AddFontFile(fonts.Value);
         var textBlock = new TextBlock
         {
             Text       = fonts.Key,
             FontFamily = new FontFamily(pfc.Families[0].Name)
         };
         pfc.Dispose();
         ComboBoxFont.Items.Add(textBlock);
         await Task.Delay(1);
     }
     GroupBoxFont.Header = "字体及字号设置";
     if (TextInstallDir.Text != "<!未找到 GameMaker Studio 2 的路径>")
     {
         default_macrosDeserialize();
         GroupBoxFont.IsEnabled = true;
     }
     isLoadFont = true;
     Log.WriteLog(Log.LogLevel.信息, "异步加载字体完毕");
 }
Exemplo n.º 3
0
        private List <string> GetFontNames(byte[] fontBytes)
        {
            var privateFontCollection = new PrivateFontCollection();
            var handle  = GCHandle.Alloc(fontBytes, GCHandleType.Pinned);
            var pointer = handle.AddrOfPinnedObject();

            try
            {
                privateFontCollection.AddMemoryFont(pointer, fontBytes.Length);
            }
            finally
            {
                handle.Free();
            }

            var resultList = new List <string>();

            foreach (var font in privateFontCollection.Families)
            {
                resultList.Add(font.Name);
            }

            privateFontCollection.Dispose();
            return(resultList);
        }
Exemplo n.º 4
0
        // ------------------------------------------------------------------

        public static List <string> GetFontNamesFromFile(string fileName)
        {
            var fontNames = new List <string>();

            if (FontUtils.IsTTFFile(fileName))
            {
                var fc = new PrivateFontCollection();
                try
                {
                    fc.AddFontFile(fileName);

                    foreach (var family in fc.Families)
                    {
                        fontNames.Add(family.Name);
                    }
                }
                catch (Exception)
                {
                    fontNames.Clear();
                }

                fc.Dispose();

                // There is a bug in PrivateFontCollection::Dispose()
                // which does not release the font file in GDI32.dll
                // This results in duplicate font names for anyone
                // calling the Win32 function EnumFonts.
                RemoveFontResourceEx(fileName, FR_PRIVATE, IntPtr.Zero);
            }

            return(fontNames);
        }
Exemplo n.º 5
0
        protected sealed override unsafe void OnFileChanged()
        {
            if (fontCollection != null)
            {
                fontCollection.Dispose();
                fontCollection = null;
                fontFamily     = null;
            }

            if (File != null)
            {
                using (var stream = File.Open())
                {
                    var buffer = new byte[stream.Length];

                    fixed(byte *bufferPointer = buffer)
                    {
                        stream.Read(bufferPointer, (int)stream.Length);

                        fontCollection = new PrivateFontCollection();
                        try { fontCollection.AddMemoryFont((IntPtr)bufferPointer, buffer.Length); }
                        catch { fontCollection = null; throw; }
                    }

                    FontFamily = fontCollection.Families[fontCollection.Families.Length - 1];
                }
            }
        }
Exemplo n.º 6
0
        /// <summary>
        /// Find the font family name of an specified TTF font file.
        /// </summary>
        /// <param name="ttfFont">TTF font file.</param>
        /// <returns>The font family name of the specified TTF font file.</returns>
        /// <remarks>This method will return an empty string if the specified font is not found in its path or the system font folder or if it is not a valid TTF font.</remarks>
        public static string TrueTypeFontFamilyName(string ttfFont)
        {
            if (string.IsNullOrEmpty(ttfFont))
            {
                throw new ArgumentNullException(nameof(ttfFont));
            }

            // the following information is only applied to TTF not SHX fonts
            if (!Path.GetExtension(ttfFont).Equals(".TTF", StringComparison.InvariantCultureIgnoreCase))
            {
                return(string.Empty);
            }

            // try to find the file in the specified directory, if not try it in the fonts system folder
            string fontFile = File.Exists(ttfFont) ?
                              Path.GetFullPath(ttfFont) :
                              string.Format("{0}{1}{2}", Environment.GetFolderPath(Environment.SpecialFolder.Fonts), Path.DirectorySeparatorChar, Path.GetFileName(ttfFont));

            PrivateFontCollection fontCollection = new PrivateFontCollection();

            try
            {
                fontCollection.AddFontFile(fontFile);
                return(fontCollection.Families[0].Name);
            }
            catch (FileNotFoundException)
            {
                return(string.Empty);
            }
            finally
            {
                fontCollection.Dispose();
            }
        }
Exemplo n.º 7
0
 /// <summary>
 /// Implement interface for disposing.
 /// </summary>
 /// <param name="disposing"></param>
 protected virtual void Dispose(bool disposing)
 {
     if (disposing)
     {
         _privateFontCollection?.Dispose();
     }
 }
Exemplo n.º 8
0
 /// <summary>
 /// 释放资源
 /// </summary>
 public void Dispose()
 {
     if (_ptf != null)
     {
         _ptf.Dispose();
         _ptf = null;
     }
 }
Exemplo n.º 9
0
        public void Dispose_Family()
        {
            PrivateFontCollection pfc = new PrivateFontCollection();

            pfc.Dispose();
            Assert.Throws <ArgumentException> (() => { var x = pfc.Families; });
            // no it's not a ObjectDisposedException
        }
Exemplo n.º 10
0
        public void AddFontFile_Disposed_ThrowsArgumentException()
        {
            var fontCollection = new PrivateFontCollection();

            fontCollection.Dispose();

            AssertExtensions.Throws <ArgumentException>(null, () => fontCollection.AddFontFile("fileName"));
        }
Exemplo n.º 11
0
        public void AddMemoryFont_Disposed_ThrowsArgumentException()
        {
            var fontCollection = new PrivateFontCollection();

            fontCollection.Dispose();

            AssertExtensions.Throws <ArgumentException>(null, () => fontCollection.AddMemoryFont((IntPtr)10, 100));
        }
Exemplo n.º 12
0
        public void Families_GetWhenDisposed_ThrowsArgumentException()
        {
            var fontCollection = new PrivateFontCollection();

            fontCollection.Dispose();

            AssertExtensions.Throws <ArgumentException>(null, () => fontCollection.Families);
        }
Exemplo n.º 13
0
        public void Dispose_Family()
        {
            PrivateFontCollection pfc = new PrivateFontCollection();

            pfc.Dispose();
            Assert.IsNotNull(pfc.Families);
            // no it's not a ObjectDisposedException
        }
Exemplo n.º 14
0
        /// <summary>
        /// Setzt die Schriftart der Engine (Schriftart sollte vom Typ 'monospace' sein)
        /// </summary>
        /// <param name="filename">Dateiname mit relativem Pfad</param>
        public static void SetFont(string filename)
        {
            Collection.Dispose();
            Collection = new PrivateFontCollection();
            HelperFont.AddFontFromFile(Collection, filename);
            Font = filename;

            HelperFont.GenerateTextures();
        }
Exemplo n.º 15
0
        private void picTestFont_Paint(object sender, PaintEventArgs e)
        {
            var ttfFilePath = Path.Combine(Path.GetDirectoryName(TTXPathTextBox.Text), Path.GetFileNameWithoutExtension(TTXPathTextBox.Text) + ".ttf");

            if (File.Exists(ttfFilePath))
            {
                PrivateFontCollection privateFontCollection = new PrivateFontCollection();

                using (var stream = File.OpenRead(ttfFilePath))
                {
                    var fontData = new byte[stream.Length];
                    stream.Read(fontData, 0, fontData.Length);
                    var fontDataPtr = Marshal.AllocCoTaskMem(fontData.Length);
                    try
                    {
                        Marshal.Copy(fontData, 0, fontDataPtr, fontData.Length);
                        privateFontCollection.AddMemoryFont(fontDataPtr, fontData.Length);
                        Thread.Sleep(100);
                    }
                    finally
                    {
                        Marshal.FreeCoTaskMem(fontDataPtr);
                    }
                }
                //privateFontCollection.AddFontFile(ttfFilePath);

                FontFamily[] fontFamilies = privateFontCollection.Families;
                Font         customFont   = new Font(fontFamilies[0], 16.0F);

                PointF     pointF     = new PointF(10, 0);
                SolidBrush solidBrush = new SolidBrush(Color.Black);

                var             showingText = TestPhraseTextBox.Text;
                MatchCollection matches     = Regex.Matches(showingText, @"\\u([0-9A-Fa-f]{4})");
                foreach (var oMatch in matches)
                {
                    var match = oMatch as Match;
                    showingText = showingText.Replace(match.Value, ((char)int.Parse(match.Groups[1].Value, System.Globalization.NumberStyles.HexNumber)).ToString());
                }

                e.Graphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
                e.Graphics.DrawString(
                    showingText,
                    customFont,
                    solidBrush,
                    pointF);

                e.Graphics.DrawString(
                    TestPhrase2TextBox.Text,
                    customFont,
                    solidBrush,
                    new PointF(pointF.X, pointF.Y + 17));

                customFont.Dispose();
                privateFontCollection.Dispose();
            }
        }
Exemplo n.º 16
0
 public void DisposeFont()
 {
     if (pfc is null)
     {
         return;
     }
     pfc.Dispose();
     Marshal.FreeCoTaskMem(fontMemory);
 }
Exemplo n.º 17
0
 /// <summary>
 /// Dumb MS logic dispose method.
 /// </summary>
 /// <param name="disposing">Whether to dispose managed resources.</param>
 protected virtual void Dispose(bool disposing)
 {
     if (disposing)
     {
         Standard.Dispose();
         CurrentBMP.Dispose();
         pfc.Dispose();
     }
 }
Exemplo n.º 18
0
        /// <summary>
        ///     Adds a font from a file.
        /// </summary>
        /// <param name="name"></param>
        /// <param name="filePath"></param>
        public static void AddFont(string name, string filePath)
        {
            var fontCollection = new PrivateFontCollection();

            fontCollection.AddFontFile(filePath);

            CustomFonts.Add(name, new FontStore(name, fontCollection.Families[0]));

            fontCollection.Dispose();
        }
Exemplo n.º 19
0
 public void Dispose()
 {
     if (_handle != null)
     {
         _handle.Free();
     }
     if (_font != null)
     {
         _font.Dispose();
     }
 }
Exemplo n.º 20
0
        public void addFonts(string[] filePaths, bool copy = true)
        {
            foreach (string fileName in filePaths)
            {
                //Console.WriteLine(fileName);
                //Console.WriteLine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData));
                FileInfo info = new FileInfo(fileName);

                // If the font list already contains this font, just skip it
                // TODO: This will only check file name. It would be nice if we
                //  could either open the font file and check font name, or exclude
                //  extension from the check, so that you can't add an OTF and TTF of
                //  the same font, for example.
                // TODO: If we *do* detect a duplicate? Perhaps show a dialog asking the
                //  user what we should do?
                if (listFonts.FindItemWithText(info.Name) != null)
                {
                    continue;
                }

                if (copy)
                {
                    try
                    {
                        File.Copy(fileName,
                                  Path.Combine(APP_DATA, info.Name),
                                  true);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Exception occured: " + ex.ToString());
                        MessageBox.Show(String.Format("Error copying {0} into fonts directory.", fileName), "Error copying file", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }
                }

                PrivateFontCollection tempCollection = new PrivateFontCollection();
                tempCollection.AddFontFile(Path.Combine(APP_DATA, info.Name));
                fonts.AddFontFile(Path.Combine(APP_DATA, info.Name));

                // Create the new item to add to the list
                string[]     data    = { tempCollection.Families[0].Name, info.Name };
                ListViewItem newItem = new ListViewItem(data);
                newItem.Checked = true;
                // TODO: User configurable font size.
                // TODO: It seems that the font goes away if you select the item before
                //   the font is installed. Should I just automatically install fonts?
                newItem.Font = new Font(tempCollection.Families[0], 12);
                listFonts.Items.Add(newItem);

                tempCollection.Dispose();
            }
        }
        public unsafe void LoadFont(byte[] fontData)
        {
            var fonts = new PrivateFontCollection();

            fixed(byte *fontPtr = fontData)
            {
                fonts.AddMemoryFont((IntPtr)fontPtr, fontData.Length);
                _fontFamily = fonts.Families[0];
                RenderLabel();
            }

            fonts.Dispose();
        }
Exemplo n.º 22
0
 private void DisposeFontResources()
 {
     if (_fontFamily != null)
     {
         _fontFamily.Dispose();
         _fontFamily = null;
     }
     if (_pfc != null)
     {
         _pfc.Dispose();
         _pfc = null;
     }
 }
Exemplo n.º 23
0
 internal void DisposeResources()
 {
     if (_fontFamily != null)
     {
         _fontFamily.Dispose();
         _fontFamily = null;
     }
     if (_pfc != null)
     {
         _pfc.Dispose();
         _pfc = null;
     }
 }
Exemplo n.º 24
0
        /// <summary>
        /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
        /// </summary>
        public void Dispose()
        {
            PrivateFontCollection ttFonts     = Interlocked.Exchange(ref _externalFonts, null);
            Lazy <GorgonFont>     defaultFont = Interlocked.Exchange(ref _defaultFont, null);

            if ((defaultFont != null) && (defaultFont.IsValueCreated))
            {
                defaultFont.Value.Dispose();
            }

            ttFonts?.Dispose();
            InvalidateCache();
        }
Exemplo n.º 25
0
 /// <summary>
 /// Clean up any resources being used.
 /// </summary>
 /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
 protected override void Dispose(bool disposing)
 {
     if (disposing)
     {
         components?.Dispose();
         _messageFont.Dispose();
         _collection?.Dispose();
         _logoBitmap.Dispose();
         _graphicsContext.Dispose();
         _fen_ControlBackgroundBrush.Dispose();
     }
     base.Dispose(disposing);
 }
Exemplo n.º 26
0
 public void Dispose()
 {
     if (!_Disposed)
     {
         if (_Fonts != null)
         {
             _Fonts.Dispose();
             _Fonts = null;
         }
         _UnloadGlyphs();
         _Disposed = true;
     }
     GC.SuppressFinalize(this);
 }
Exemplo n.º 27
0
        /// <summary>
        ///     Adds a font from memory/resource store.
        /// </summary>
        /// <param name="name">The name of the font to use for the store.</param>
        /// <param name="fontBytes"></param>
        public static void AddFont(string name, byte[] fontBytes)
        {
            var fontData = Marshal.AllocCoTaskMem(fontBytes.Length);

            Marshal.Copy(fontBytes, 0, fontData, fontBytes.Length);

            var fontCollection = new PrivateFontCollection();

            fontCollection.AddMemoryFont(fontData, fontBytes.Length);

            CustomFonts.Add(name, new FontStore(name, fontCollection.Families[0]));

            fontCollection.Dispose();
        }
Exemplo n.º 28
0
        private void MainForm_Load(object sender, EventArgs e)
        {
            lblDate.Font = new Font(familyName: "Arial", 12, FontStyle.Bold);
            PrivateFontCollection pfc = new PrivateFontCollection();

            try
            {
                pfc.AddFontFile(@"font_for_time.ttf");
                lblTime.Font = new Font(pfc.Families[0], 18, FontStyle.Regular);
            }
            catch (Exception)
            {
                lblTime.Font = new Font(familyName: "Arial Rounded MT Bold", 18, FontStyle.Regular);
            }
            pfc.Dispose();
        }
Exemplo n.º 29
0
        private bool disposedValue = false; // Para detectar llamadas redundantes

        protected virtual void Dispose(bool disposing)
        {
            if (!disposedValue)
            {
                if (disposing)
                {
                    // TODO: elimine el estado administrado (objetos administrados).
                    fonts.Dispose();
                }

                // TODO: libere los recursos no administrados (objetos no administrados) y reemplace el siguiente finalizador.
                // TODO: configure los campos grandes en nulos.

                disposedValue = true;
            }
        }
Exemplo n.º 30
0
        public void ShowFont(byte[] fontBytes)
        {
            if (pictureBox1.Width <= 1 || pictureBox1.Height <= 1)
            {
                return;
            }

            var privateFontCollection = new PrivateFontCollection();
            var handle  = GCHandle.Alloc(fontBytes, GCHandleType.Pinned);
            var pointer = handle.AddrOfPinnedObject();

            try
            {
                privateFontCollection.AddMemoryFont(pointer, fontBytes.Length);
            }
            finally
            {
                handle.Free();
            }

            var fontFamily = privateFontCollection.Families.FirstOrDefault();

            if (fontFamily == null)
            {
                return;
            }

            labelInfo.Text      = "Font name:";
            textBoxInfo.Text    = fontFamily.Name;
            textBoxInfo.Left    = labelInfo.Left + labelInfo.Width + 5;
            labelInfo.Visible   = true;
            textBoxInfo.Visible = true;

            pictureBox1.Image?.Dispose();
            pictureBox1.Image = new Bitmap(pictureBox1.Width, pictureBox1.Height);
            using (var font = new Font(fontFamily, 25, FontStyle.Regular))
                using (var G = Graphics.FromImage(pictureBox1.Image))
                {
                    G.DrawString(fontFamily.Name + Environment.NewLine +
                                 Environment.NewLine +
                                 "Hello World!" + Environment.NewLine +
                                 "こんにちは世界" + Environment.NewLine +
                                 "你好世界!" + Environment.NewLine +
                                 "1234567890", font, Brushes.Orange, 12f, 23);
                }
            privateFontCollection.Dispose();
        }
Exemplo n.º 31
0
    //Generate Tire Barcode Image
    private bool GenerateBarCodeImage(Guid g)
    {
        try
        {
            if (hdnBarCodeImageFileName.Value != "")
            {
                if (System.IO.File.Exists(Server.MapPath(String.Format("/Images/temp/{0}", hdnBarCodeImageFileName.Value))))
                {
                    System.IO.File.Delete(Server.MapPath(String.Format("/Images/temp/{0}", hdnBarCodeImageFileName.Value)));
                }
                hdnBarCodeImageFileName.Value = "";
            }
            string Code = txtDOTPlant.Text.Trim() + "-" + txtDOTSize.Text.Trim() + "-" + txtDOTBrand.Text.Trim() + "-" + txtDOTWeek.Text.Trim() + "-" + txtDOTYear.Text.Trim();

            Bitmap oBitmap = new Bitmap((Code.Length * 30), 110);

            Graphics oGraphics = Graphics.FromImage(oBitmap);
            oGraphics.FillRectangle(new SolidBrush(Color.White), 0, 0, (Code.Length * 30), 110);

            PrivateFontCollection pfc = new PrivateFontCollection();
            pfc.AddFontFile(Server.MapPath("/Font/IDAutomationHC39M.ttf"));
            Font oFont = new Font(pfc.Families[0], 18);

            oGraphics.DrawString("*" + Code + "*", oFont, new SolidBrush(Color.Black), 20, 10);

            oBitmap.Save(Server.MapPath(String.Format("/Images/temp/{0}.Gif", g)), System.Drawing.Imaging.ImageFormat.Gif);

            oBitmap.Dispose();
            oGraphics.Dispose();
            oFont.Dispose();
            pfc.Dispose();

            oBitmap = null;
            oGraphics = null;
            oFont = null;
            pfc = null;
        }
        catch (Exception ex)
        {
            new SqlLog().InsertSqlLog(currentUserInfo.UserId, "GenerateBarCodeImageAndBytes", ex);
            return false;
        }

        return true;
    }