Пример #1
0
        /// <summary>
        ///  Creates the font handle.
        /// </summary>
        private unsafe WindowsFont(NativeMethods.LOGFONTW logFont, FontStyle style, bool createHandle)
        {
            Debug.Assert(Hfont == IntPtr.Zero, "hFont is not null, this will generate a handle leak.");

            _logFont = logFont;
            if (_logFont.FaceName.Length == 0)
            {
                _logFont.FaceName = DefaultFaceName;
            }
            Style = style;

            if (createHandle)
            {
                Hfont = IntUnsafeNativeMethods.CreateFontIndirectW(ref _logFont);

                if (Hfont == IntPtr.Zero)
                {
                    _logFont.FaceName       = DefaultFaceName;
                    _logFont.lfOutPrecision = IntNativeMethods.OUT_TT_ONLY_PRECIS; // TrueType only.

                    Hfont = IntUnsafeNativeMethods.CreateFontIndirectW(ref _logFont);
                }

                // Update logFont height and other adjusted parameters.
                IntUnsafeNativeMethods.GetObjectW(new HandleRef(this, Hfont), sizeof(NativeMethods.LOGFONTW), ref _logFont);

                // We created the hFont, we will delete it on dispose.
                _ownHandle = true;
            }
        }
Пример #2
0
        /// <summary>
        ///  Creates a WindowsFont from the handle to a native GDI font and optionally takes ownership of managing
        ///  the lifetime of the handle.
        /// </summary>
        public unsafe static WindowsFont FromHfont(IntPtr hFont, bool takeOwnership = false)
        {
            NativeMethods.LOGFONTW logFont = new NativeMethods.LOGFONTW();
            IntUnsafeNativeMethods.GetObjectW(new HandleRef(null, hFont), sizeof(NativeMethods.LOGFONTW), ref logFont);

            FontStyle style = FontStyle.Regular;

            if (logFont.lfWeight == IntNativeMethods.FW_BOLD)
            {
                style |= FontStyle.Bold;
            }
            if (logFont.lfItalic == True)
            {
                style |= FontStyle.Italic;
            }
            if (logFont.lfUnderline == True)
            {
                style |= FontStyle.Underline;
            }
            if (logFont.lfStrikeOut == True)
            {
                style |= FontStyle.Strikeout;
            }

            WindowsFont wf = new WindowsFont(logFont, style, createHandle: false)
            {
                Hfont      = hFont,
                _ownHandle = takeOwnership // if true, hFont will be deleted on dispose.
            };

            return(wf);
        }