Exemple #1
0
        /// <include file='doc\FontDialog.uex' path='docs/doc[@for="FontDialog.UpdateFont"]/*' />
        /// <devdoc>
        /// </devdoc>
        /// <internalonly/>
        private void UpdateFont(NativeMethods.LOGFONT lf)
        {
            IntPtr screenDC = UnsafeNativeMethods.GetDC(NativeMethods.NullHandleRef);

            try {
                Font fontInWorldUnits = null;
                try {
                    IntSecurity.UnmanagedCode.Assert();
                    try {
                        fontInWorldUnits = Font.FromLogFont(lf, screenDC);
                    }
                    finally {
                        CodeAccessPermission.RevertAssert();
                    }

                    // The dialog claims its working in points (a device-independent unit),
                    // but actually gives us something in world units (device-dependent).
                    font = ControlPaint.FontInPoints(fontInWorldUnits);
                }
                finally {
                    if (fontInWorldUnits != null)
                    {
                        fontInWorldUnits.Dispose();
                    }
                }
            }
            finally {
                UnsafeNativeMethods.ReleaseDC(NativeMethods.NullHandleRef, new HandleRef(null, screenDC));
            }
        }
        /// <include file='doc\StyleBuilderSite.uex' path='docs/doc[@for="StyleBuilderSite.GetUIFont"]/*' />
        /// <devdoc>
        /// </devdoc>
        public Font GetUIFont()
        {
            Font uiFont = null;

            if (site != null)
            {
                try {
                    IUIHostLocale uiService = (IUIHostLocale)QueryService(typeof(IUIHostLocale));
                    _LOGFONTW     lfUnicode = new _LOGFONTW();

                    uiService.GetDialogFont(lfUnicode);

                    NativeMethods.LOGFONT lfAuto = lfUnicode.ToLOGFONT_Internal();
                    uiFont = Font.FromLogFont(lfAuto);
                }
                catch (Exception e) {
                    Debug.Fail(e.ToString());
                }
            }
            if (uiFont == null)
            {
                try {
                    // this is what VS returns...
                    uiFont = new Font("Tahoma", 11, FontStyle.Regular, GraphicsUnit.World);
                }
                catch {
                    uiFont = Control.DefaultFont;
                }
            }
            return(uiFont);
        }
Exemple #3
0
        internal NativeMethods.LOGFONT ToLOGFONT_Internal()
        {
            _LOGFONTW lfUnicode = this;

            // No way today to define a char array in IDL that is interop compatible, so
            // we've got to read everything in here!
            //
            StringBuilder sb = new StringBuilder();
            int           ch = 0;

            while (ch < 32)
            {
                FieldInfo fi = (typeof(_LOGFONTW)).GetField("lfFaceName" + ch.ToString());
                if (fi == null)
                {
                    break;
                }
                Object o = fi.GetValue(this);
                try {
                    short charVal = (short)o;
                    if (charVal == 0)
                    {
                        break;
                    }
                    sb.Append((char)charVal);
                }
                catch (InvalidCastException) {
                    return(null);
                }
                ch++;
            }

            // Copy one LOGFONT to the other...
            NativeMethods.LOGFONT lfAuto = new NativeMethods.LOGFONT();
            lfAuto.lfHeight         = lfUnicode.lfHeight;
            lfAuto.lfWidth          = lfUnicode.lfWidth;
            lfAuto.lfEscapement     = lfUnicode.lfEscapement;
            lfAuto.lfOrientation    = lfUnicode.lfOrientation;
            lfAuto.lfWeight         = lfUnicode.lfWeight;
            lfAuto.lfItalic         = lfUnicode.lfItalic;
            lfAuto.lfUnderline      = lfUnicode.lfUnderline;
            lfAuto.lfStrikeOut      = lfUnicode.lfStrikeOut;
            lfAuto.lfCharSet        = lfUnicode.lfCharSet;
            lfAuto.lfOutPrecision   = lfUnicode.lfOutPrecision;
            lfAuto.lfClipPrecision  = lfUnicode.lfClipPrecision;
            lfAuto.lfQuality        = lfUnicode.lfQuality;
            lfAuto.lfPitchAndFamily = lfUnicode.lfPitchAndFamily;
            lfAuto.lfFaceName       = sb.ToString();

            return(lfAuto);
        }
Exemple #4
0
        internal NativeMethods.LOGFONT GetLogfont()
        {
            IntPtr hfont = GetFont();

            Debug.Assert(hfont != IntPtr.Zero, "WindowsEditBox.GetLogfont got null HFONT");
            NativeMethods.LOGFONT logfont = new NativeMethods.LOGFONT();
            int cb = Marshal.SizeOf(typeof(NativeMethods.LOGFONT));

            if (Misc.GetObjectW(hfont, cb, ref logfont) != cb)
            {
                Debug.Assert(false, "WindowsEditBox.GetObject unexpected return value");
            }
            return(logfont);
        }
        // returns the value of the corresponding text attribute
        private static object GetFontSize(NativeMethods.LOGFONT logfont)
        {
            // note: this assumes integral point sizes. violating this assumption would confuse the user
            // because they set something to 7 point but reports that it is, say 7.2 point, due to the rounding.
            IntPtr hdc = Misc.GetDC(IntPtr.Zero);

            if (hdc == IntPtr.Zero)
            {
                return(null);
            }
            int lpy = UnsafeNativeMethods.GetDeviceCaps(hdc, NativeMethods.LOGPIXELSY);

            Misc.ReleaseDC(IntPtr.Zero, hdc);
            return(Math.Round((double)(-logfont.lfHeight) * 72 / lpy));
        }
Exemple #6
0
        /// <include file='doc\FontDialog.uex' path='docs/doc[@for="FontDialog.HookProc"]/*' />
        /// <devdoc>
        ///    <para>
        ///       Specifies the common dialog box hook procedure that is overridden to add
        ///       specific functionality to a common dialog box.
        ///    </para>
        /// </devdoc>
        protected override IntPtr HookProc(IntPtr hWnd, int msg, IntPtr wparam, IntPtr lparam)
        {
            switch (msg)
            {
            case NativeMethods.WM_COMMAND:
                if ((int)wparam == 0x402)
                {
                    NativeMethods.LOGFONT lf = new NativeMethods.LOGFONT();
                    UnsafeNativeMethods.SendMessage(new HandleRef(null, hWnd), NativeMethods.WM_CHOOSEFONT_GETLOGFONT, 0, lf);
                    UpdateFont(lf);
                    int index = (int)UnsafeNativeMethods.SendDlgItemMessage(new HandleRef(null, hWnd), 0x473, NativeMethods.CB_GETCURSEL, IntPtr.Zero, IntPtr.Zero);
                    if (index != NativeMethods.CB_ERR)
                    {
                        UpdateColor((int)UnsafeNativeMethods.SendDlgItemMessage(new HandleRef(null, hWnd), 0x473,
                                                                                NativeMethods.CB_GETITEMDATA, (IntPtr)index, IntPtr.Zero));
                    }
                    if (NativeWindow.WndProcShouldBeDebuggable)
                    {
                        OnApply(EventArgs.Empty);
                    }
                    else
                    {
                        try
                        {
                            OnApply(EventArgs.Empty);
                        }
                        catch (Exception e)
                        {
                            Application.OnThreadException(e);
                        }
                    }
                }
                break;

            case NativeMethods.WM_INITDIALOG:
                if (!showColor)
                {
                    IntPtr hWndCtl = UnsafeNativeMethods.GetDlgItem(new HandleRef(null, hWnd), NativeMethods.cmb4);
                    SafeNativeMethods.ShowWindow(new HandleRef(null, hWndCtl), NativeMethods.SW_HIDE);
                    hWndCtl = UnsafeNativeMethods.GetDlgItem(new HandleRef(null, hWnd), NativeMethods.stc4);
                    SafeNativeMethods.ShowWindow(new HandleRef(null, hWndCtl), NativeMethods.SW_HIDE);
                }
                break;
            }

            return(base.HookProc(hWnd, msg, wparam, lparam));
        }
        public Font GetFont(IDeviceContext dc, FontProperty prop)
        {
            if (dc == null)
            {
                throw new ArgumentNullException(nameof(dc));
            }

            //valid values are 0xa29 to 0xa29
            if (!ClientUtils.IsEnumValid(prop, (int)prop, (int)FontProperty.GlyphFont, (int)FontProperty.GlyphFont))
            {
                throw new InvalidEnumArgumentException(nameof(prop), (int)prop, typeof(FontProperty));
            }

            NativeMethods.LOGFONT logfont = new NativeMethods.LOGFONT();

            using (WindowsGraphicsWrapper wgr = new WindowsGraphicsWrapper(dc, AllGraphicsProperties))
            {
                HandleRef hdc = new HandleRef(wgr, wgr.WindowsGraphics.DeviceContext.Hdc);
                lastHResult = SafeNativeMethods.GetThemeFont(new HandleRef(this, Handle), hdc, part, state, (int)prop, logfont);
            }

            Font font = null;

            //check for a failed HR.
            if (NativeMethods.Succeeded(lastHResult))
            {
                try
                {
                    font = Font.FromLogFont(logfont);
                }
                catch (Exception e)
                {
                    if (ClientUtils.IsSecurityOrCriticalException(e))
                    {
                        throw;
                    }

                    //Looks like the font was not true type
                    font = null;
                }
            }

            return(font);
        }
Exemple #8
0
        public MainForm()
        {
            InitializeComponent();

            Graphics graphics = Graphics.FromHwnd(this.Handle);
            IntPtr hdc = graphics.GetHdc();
            var logfont = new NativeMethods.LOGFONT() { lfCharSet = NativeMethods.DEFAULT_CHARSET };
            NativeMethods.EnumFontFamiliesEx(hdc, ref logfont, new NativeMethods.FONTENUMPROC(EnumFontFamExProc), IntPtr.Zero, 0);
            graphics.ReleaseHdc();

            if (comboBoxFontFamily.Items.Count > 0)
            {
                if (comboBoxFontFamily.Items.Contains("Consolas"))
                {
                    comboBoxFontFamily.Text = "Consolas";
                }
                else
                {
                    comboBoxFontFamily.SelectedIndex = 0;
                }
            }
        }
        internal static Font GetFontFromShell(IUIHostLocale locale)
        {
            _LOGFONTW font = new _LOGFONTW();

            locale.GetDialogFont(font);

            NativeMethods.LOGFONT lfAuto = font.ToLOGFONT_Internal();
            Font shellFont = null;

            if (lfAuto != null)
            {
                try {
                    shellFont = Font.FromLogFont(lfAuto);
                }
                catch (ArgumentException) {
                }
            }
            if (shellFont == null)
            {
                shellFont = Control.DefaultFont;
            }

            return(shellFont);
        }
 // returns the value of the corresponding text attribute
 private static object GetItalic(NativeMethods.LOGFONT logfont)
 {
     return(logfont.lfItalic != 0);
 }
    /// <summary>
    /// Defines the common dialog box hook procedure that is overridden to add specific functionality to a common dialog box.
    /// </summary>
    /// <returns>
    /// A zero value if the default dialog box procedure processes the message; a nonzero value if the default dialog box procedure ignores the message.
    /// </returns>
    /// <param name="hWnd">The handle to the dialog box window. </param><param name="msg">The message being received. </param><param name="wparam">Additional information about the message. </param><param name="lparam">Additional information about the message. </param>
    protected override IntPtr HookProc(IntPtr hWnd, int msg, IntPtr wparam, IntPtr lparam)
    {
      // This code is lifted directly from System.Windows.Forms.FontDialog

      switch (msg)
      {
        case NativeMethods.WM_COMMAND:
          if ((int)wparam == 0x402)
          {
            NativeMethods.LOGFONT lf = new NativeMethods.LOGFONT();
            NativeMethods.SendMessage(new HandleRef(null, hWnd), NativeMethods.WM_CHOOSEFONT_GETLOGFONT, 0, lf);
            this.UpdateFont(lf);
            int index = (int)NativeMethods.SendDlgItemMessage(new HandleRef(null, hWnd), 0x473, NativeMethods.CB_GETCURSEL, IntPtr.Zero, IntPtr.Zero);
            if (index != NativeMethods.CB_ERR)
            {
              this.UpdateColor((int)NativeMethods.SendDlgItemMessage(new HandleRef(null, hWnd), 0x473, NativeMethods.CB_GETITEMDATA, (IntPtr)index, IntPtr.Zero));
            }

            try
            {
              this.OnApply(EventArgs.Empty);
            }
            catch (Exception e)
            {
              Application.OnThreadException(e);
            }
          }
          break;
        case NativeMethods.WM_INITDIALOG:
          if (!this.ShowColor)
          {
            IntPtr hWndCtl = NativeMethods.GetDlgItem(new HandleRef(null, hWnd), NativeMethods.cmb4);
            NativeMethods.ShowWindow(new HandleRef(null, hWndCtl), NativeMethods.SW_HIDE);
            hWndCtl = NativeMethods.GetDlgItem(new HandleRef(null, hWnd), NativeMethods.stc4);
            NativeMethods.ShowWindow(new HandleRef(null, hWndCtl), NativeMethods.SW_HIDE);
          }
          break;
      }

      return base.HookProc(hWnd, msg, wparam, lparam);
    }
Exemple #12
0
        static byte[] ReadFontBytesFromGdi(GdiFont gdiFont)
        {
            // Weird: LastError is always 123 or 127. Comment out Debug.Assert.
            int error = Marshal.GetLastWin32Error();

            //Debug.Assert(error == 0);
            error = Marshal.GetLastWin32Error();
            //Debug.Assert(error == 0);

            IntPtr hfont = gdiFont.ToHfont();

#if true
            IntPtr hdc = NativeMethods.GetDC(IntPtr.Zero);
#else
            NativeMethods.LOGFONT logFont = new NativeMethods.LOGFONT();
            logFont.lfHeight         = 30;
            logFont.lfWidth          = 0;
            logFont.lfEscapement     = 0;
            logFont.lfOrientation    = 0;
            logFont.lfWeight         = 400;
            logFont.lfItalic         = 0;
            logFont.lfUnderline      = 0;
            logFont.lfStrikeOut      = 0;
            logFont.lfCharSet        = 0;
            logFont.lfOutPrecision   = 0;
            logFont.lfClipPrecision  = 0;
            logFont.lfQuality        = 0;
            logFont.lfPitchAndFamily = 0;
            logFont.lfFaceName       = "Arial";

            gdiFont.ToLogFont(logFont);

            hfont = NativeMethods.CreateFontIndirect(logFont);


            // IntPtr hdc = NativeMethods.CreateDC("DISPLAY", null, null, IntPtr.Zero);
            IntPtr hdc = NativeMethods.CreateCompatibleDC(IntPtr.Zero);
#endif
            error = Marshal.GetLastWin32Error();
            //Debug.Assert(error == 0);

            IntPtr oldFont = NativeMethods.SelectObject(hdc, hfont);
            error = Marshal.GetLastWin32Error();
            //Debug.Assert(error == 0);

            // Get size of the font file.
            bool isTtcf = false;
            // In Azure I get 0xc0000022
            int size = NativeMethods.GetFontData(hdc, 0, 0, null, 0);

            // Check for ntstatus.h: #define STATUS_ACCESS_DENIED             ((NTSTATUS)0xC0000022L)
            if ((uint)size == 0xc0000022)
            {
                throw new InvalidOperationException("Microsoft Azure returns STATUS_ACCESS_DENIED ((NTSTATUS)0xC0000022L) from GetFontData. This is a bug in Azure. You must implement a FontResolver to circumvent this issue.");
            }

            if (size == NativeMethods.GDI_ERROR)
            {
                // Assume that the font file is a true type collection.
                size   = NativeMethods.GetFontData(hdc, ttcf, 0, null, 0);
                isTtcf = true;
            }
            error = Marshal.GetLastWin32Error();
            //Debug.Assert(error == 0);

            if (size == 0)
            {
                throw new InvalidOperationException("Cannot retrieve font data.");
            }

            byte[] bytes         = new byte[size];
            int    effectiveSize = NativeMethods.GetFontData(hdc, isTtcf ? ttcf : 0, 0, bytes, size);
            Debug.Assert(size == effectiveSize);
            // Clean up.
            NativeMethods.SelectObject(hdc, oldFont);
            NativeMethods.ReleaseDC(IntPtr.Zero, hdc);

            return(bytes);
        }
    /// <summary>
    /// When overridden in a derived class, specifies a common dialog box.
    /// </summary>
    /// <returns>
    /// true if the dialog box was successfully run; otherwise, false.
    /// </returns>
    /// <param name="hwndOwner">A value that represents the window handle of the owner window for the common dialog box. </param>
    protected override bool RunDialog(IntPtr hwndOwner)
    {
      NativeMethods.LOGFONT lf;
      NativeMethods.CHOOSEFONT cf;
      IntPtr plf;
      bool result;
      int minSize;
      int maxSize;
      bool showColor;

      lf = new NativeMethods.LOGFONT();

      this.Font.ToLogFont(lf);

      plf = Marshal.AllocHGlobal(Marshal.SizeOf(lf));
      Marshal.StructureToPtr(lf, plf, false);

      showColor = this.ShowColor || this.ShowEffects;

      cf = new NativeMethods.CHOOSEFONT();
      cf.lStructSize = Marshal.SizeOf(typeof(NativeMethods.CHOOSEFONT));
      cf.Flags = this.GetFlags();
      cf.hwndOwner = hwndOwner;
      cf.lpfnHook = this.HookProc;

      minSize = this.MinSize;
      maxSize = this.MaxSize;
      if (minSize > 0 || maxSize > 0)
      {
        cf.nSizeMin = minSize;
        cf.nSizeMax = maxSize > 0 ? maxSize : int.MaxValue;
      }

      cf.rgbColors = ColorTranslator.ToWin32(showColor ? this.Color : Color.Black);

      cf.lpLogFont = plf;

      try
      {
        result = NativeMethods.ChooseFont(ref cf);

        if (result)
        {
          // create a managed font from the updated LOGFONT
          lf = (NativeMethods.LOGFONT)Marshal.PtrToStructure(plf, typeof(NativeMethods.LOGFONT));
          if (!string.IsNullOrEmpty(lf.lfFaceName))
          {
            this.UpdateFont(lf);
          }

          // and update the color
          if (showColor)
          {
            this.UpdateColor(cf.rgbColors);
          }
        }
      }
      finally
      {
        // always be freein' allocated memory!
        Marshal.FreeHGlobal(plf);
      }

      return result;
    }
Exemple #14
0
        /// <summary>
        /// Create the font image using GDI+ functionality.
        /// </summary>
        void CreateGdiFontImage(XFont font, XPdfFontOptions options, XPrivateFontCollection privateFontCollection)
        {
            System.Drawing.Font   gdiFont = font.RealizeGdiFont();
            NativeMethods.LOGFONT logFont;
#if DEBUG_
            logFont = new NativeMethods.LOGFONT();
            gdiFont.ToLogFont(logFont);
            Debug.WriteLine("FontData: " + logFont.lfFaceName);
#endif
            this.data = null;
            if (privateFontCollection != null)
            {
                //XPrivateFont privateFont = privateFontCollection.FindFont(logFont.lfFaceName, logFont.lfWeight >= 700, logFont.lfItalic > 0);
                XPrivateFont privateFont = privateFontCollection.FindFont(font.Name, font.Bold, font.Italic);
                if (privateFont != null)
                {
                    int size = privateFont.GetFontData(ref this.data, 0);
                    if (size > 0)
                    {
                        this.data = new byte[size];
                        privateFont.GetFontData(ref this.data, size);
                    }
                }
            }
            if (this.data == null)
            {
                int    error;
                IntPtr hfont = gdiFont.ToHfont();
                IntPtr hdc   = NativeMethods.GetDC(IntPtr.Zero);
                error = Marshal.GetLastWin32Error();
                IntPtr oldFont = NativeMethods.SelectObject(hdc, hfont);
                error = Marshal.GetLastWin32Error();
                // size is exactly the size of the font file.
                int size = NativeMethods.GetFontData(hdc, 0, 0, null, 0);
                error = Marshal.GetLastWin32Error();
                if (size > 0)
                {
                    this.data = new byte[size];
                    int effectiveSize = NativeMethods.GetFontData(hdc, 0, 0, this.data, this.data.Length);
                    Debug.Assert(size == effectiveSize);
                    NativeMethods.SelectObject(hdc, oldFont);
                    NativeMethods.ReleaseDC(IntPtr.Zero, hdc);
                    error.GetType();
                }
                else
                {
                    // Sometimes size is -1 (GDI_ERROR), but I cannot determine why. It happens only with the font 'Symbol'.
                    // The issue occurs the first time in early 2005, when I start writing PDFsharp. I could not fix it and after
                    // some code refactoring the problem disappears.
                    // There was never a report from anyone about this issue.
                    // Now I get it again (while debugging QBX 2006). Maybe it is a problem with my PC at my home office.
                    // As a work-around I create a new font handle with a different height value. This works. Maybe the
                    // font file gets locked somewhere. Very very strange.

                    // IF SOMEONE ELSE COMES HERE PLEASE LET ME KNOW!

                    // Clean up old handles
                    NativeMethods.SelectObject(hdc, oldFont);
                    NativeMethods.ReleaseDC(IntPtr.Zero, hdc);

                    // Try again with new font handle
                    logFont = new NativeMethods.LOGFONT();
                    gdiFont.ToLogFont(logFont);
                    logFont.lfHeight += 1; // force new handle
                    IntPtr hfont2 = NativeMethods.CreateFontIndirect(logFont);
                    hdc     = NativeMethods.GetDC(IntPtr.Zero);
                    error   = Marshal.GetLastWin32Error();
                    oldFont = NativeMethods.SelectObject(hdc, hfont2);
                    error   = Marshal.GetLastWin32Error();
                    // size is exactly the size of the font file.
                    size  = NativeMethods.GetFontData(hdc, 0, 0, null, 0);
                    error = Marshal.GetLastWin32Error();
                    if (size > 0)
                    {
                        this.data = new byte[size];
                        int effectiveSize = NativeMethods.GetFontData(hdc, 0, 0, this.data, this.data.Length);
                        Debug.Assert(size == effectiveSize);
                    }
                    NativeMethods.SelectObject(hdc, oldFont);
                    NativeMethods.ReleaseDC(IntPtr.Zero, hdc);
                    NativeMethods.DeleteObject(hfont2);
                    error.GetType();
                }
            }
            if (this.data == null)
            {
                throw new InvalidOperationException("Internal error. Font data could not retrieved.");
            }
        }
 public static extern int GetThemeFont(HandleRef hTheme, HandleRef hdc, int iPartId, int iStateId, int iPropId, NativeMethods.LOGFONT pFont);
 // returns the value of the corresponding text attribute
 private static object GetUnderlineStyle(NativeMethods.LOGFONT logfont)
 {
     return(logfont.lfUnderline != 0 ? TextDecorationLineStyle.Single : TextDecorationLineStyle.None);
 }
Exemple #17
0
        /// <summary>
        /// Create the font image using GDI+ functionality.
        /// </summary>
        void CreateGdiFontImage(XFont font, XPdfFontOptions options /*, XPrivateFontCollection privateFontCollection*/)
        {
            System.Drawing.Font gdiFont = font.RealizeGdiFont();
#if DEBUG_
            logFont = new NativeMethods.LOGFONT();
            gdiFont.ToLogFont(logFont);
            Debug.WriteLine("FontData: " + logFont.lfFaceName);
#endif
            this.data = null;

            // PFC
            //if (privateFontCollection != null)
            //{
            //  //XPrivateFont privateFont = privateFontCollection.FindFont(logFont.lfFaceName, logFont.lfWeight >= 700, logFont.lfItalic > 0);
            //  XGlyphTypeface privateFont = privateFontCollection.FindFont(font.Name, font.Bold, font.Italic);
            //  if (privateFont != null)
            //  {
            //    //////int size = privateFont.GetData(ref this.data);
            //    //////if (size > 0)
            //    //////{
            //    //////  this.data = new byte[size];
            //    //////  privateFont.GetData(ref this.data, size);
            //    //////}
            //  }
            //}
            if (this.data == null)
            {
                var assembly = FontDataConfig.ResourceAssembly;
                var name     = string.Format("{0}.FontHacks.{1}{2}{3}.fontdat",
                                             assembly != null ? assembly.GetName().Name : string.Empty,
                                             font.Name,
                                             font.Bold ? ".Bold" : string.Empty,
                                             font.Italic ? ".Italic" : string.Empty);
                if (assembly != null && new List <string>(assembly.GetManifestResourceNames()).Contains(name))
                {
                    System.Diagnostics.Debug.WriteLine("*** Reading fontdata from Resource");
                    using (var s = assembly.GetManifestResourceStream(name))
                    {
                        this.data = new byte[s.Length];
                        s.Read(this.data, 0, (int)s.Length);
                    }
                }
                else
                {
                    System.Diagnostics.Debug.WriteLine("*** Reading fontdata from GDI+");
                    int    error;
                    IntPtr hfont = gdiFont.ToHfont();
                    using (var dcBmp = new Bitmap(100, 100))
                        using (var dc = Graphics.FromImage(dcBmp))
                        {
                            IntPtr hdc = dc.GetHdc();
                            error = Marshal.GetLastWin32Error();
                            IntPtr oldFont = NativeMethods.SelectObject(hdc, hfont);
                            error = Marshal.GetLastWin32Error();
                            // size is exactly the size of the font file.
                            int size = NativeMethods.GetFontData(hdc, 0, 0, null, 0);
                            error = Marshal.GetLastWin32Error();
                            if (size > 0)
                            {
                                this.data = new byte[size];
                                int effectiveSize = NativeMethods.GetFontData(hdc, 0, 0, this.data, this.data.Length);
                                Debug.Assert(size == effectiveSize);
                                if (FontDataConfig.SaveFont)
                                {
                                    FileExtensions.WriteFileBytes(this.data, string.Format("..\\..\\FontHacks\\{0}{1}{2}.fontdat",
                                                                                           font.Name,
                                                                                           font.Bold ? ".Bold" : string.Empty,
                                                                                           font.Italic ? ".Italic" : string.Empty));
                                }
                                NativeMethods.SelectObject(hdc, oldFont);
                                NativeMethods.ReleaseDC(IntPtr.Zero, hdc);
                                error.GetType();
                            }
                            else
                            {
                                // Sometimes size is -1 (GDI_ERROR), but I cannot determine why. It happens only with the font 'Symbol'.
                                // The issue occurs the first time in early 2005, when I start writing PDFsharp. I could not fix it and after
                                // some code refactoring the problem disappears.
                                // There was never a report from anyone about this issue.
                                // Now I get it again (while debugging QBX 2006). Maybe it is a problem with my PC at my home office.
                                // As a work-around I create a new font handle with a different height value. This works. Maybe the
                                // font file gets locked somewhere. Very very strange.

                                // IF SOMEONE ELSE COMES HERE PLEASE LET ME KNOW!

                                // Clean up old handles
                                NativeMethods.SelectObject(hdc, oldFont);
                                NativeMethods.ReleaseDC(IntPtr.Zero, hdc);

                                // Try again with new font handle
                                var logFont = new NativeMethods.LOGFONT();
                                gdiFont.ToLogFont(logFont);
                                logFont.lfHeight += 1; // force new handle
                                IntPtr hfont2 = NativeMethods.CreateFontIndirect(logFont);
                                hdc     = NativeMethods.GetDC(IntPtr.Zero);
                                error   = Marshal.GetLastWin32Error();
                                oldFont = NativeMethods.SelectObject(hdc, hfont2);
                                error   = Marshal.GetLastWin32Error();
                                // size is exactly the size of the font file.
                                size  = NativeMethods.GetFontData(hdc, 0, 0, null, 0);
                                error = Marshal.GetLastWin32Error();
                                if (size > 0)
                                {
                                    this.data = new byte[size];
                                    int effectiveSize = NativeMethods.GetFontData(hdc, 0, 0, this.data, this.data.Length);
                                    Debug.Assert(size == effectiveSize);
                                }
                                NativeMethods.SelectObject(hdc, oldFont);
                                NativeMethods.ReleaseDC(IntPtr.Zero, hdc);
                                NativeMethods.DeleteObject(hfont2);
                                error.GetType();
                            }
                        }
                }
                if (this.data == null)
                {
                    throw new InvalidOperationException("Internal error. Font data could not retrieved.");
                }
            }
        }
Exemple #18
0
 internal static extern int GetObjectW(IntPtr hObject, int size, ref NativeMethods.LOGFONT lf);
 // returns the value of the corresponding text attribute
 private static object GetFontWeight(NativeMethods.LOGFONT logfont)
 {
     return(logfont.lfWeight);
 }
 // returns the value of the corresponding text attribute
 private static object GetFontName(NativeMethods.LOGFONT logfont)
 {
     return(logfont.lfFaceName);
 }
Exemple #21
0
        /// <include file='doc\FontDialog.uex' path='docs/doc[@for="FontDialog.RunDialog"]/*' />
        /// <internalonly/>
        /// <devdoc>
        ///    <para>
        ///       The actual implementation of running the dialog. Inheriting classes
        ///       should override this if they want to add more functionality, and call
        ///       base.runDialog() if necessary
        ///
        ///    </para>
        /// </devdoc>
        protected override bool RunDialog(IntPtr hWndOwner)
        {
            NativeMethods.WndProc    hookProcPtr = new NativeMethods.WndProc(this.HookProc);
            NativeMethods.CHOOSEFONT cf          = new NativeMethods.CHOOSEFONT();
            IntPtr screenDC = UnsafeNativeMethods.GetDC(NativeMethods.NullHandleRef);

            NativeMethods.LOGFONT lf = new NativeMethods.LOGFONT();

            Graphics graphics = Graphics.FromHdcInternal(screenDC);

            try {
                Font.ToLogFont(lf, graphics);
            }
            finally {
                graphics.Dispose();
            }
            UnsafeNativeMethods.ReleaseDC(NativeMethods.NullHandleRef, new HandleRef(null, screenDC));

            IntPtr logFontPtr = IntPtr.Zero;

            try {
                logFontPtr = Marshal.AllocCoTaskMem(Marshal.SizeOf(typeof(NativeMethods.LOGFONT)));
                Marshal.StructureToPtr(lf, logFontPtr, false);

                cf.lStructSize = Marshal.SizeOf(typeof(NativeMethods.CHOOSEFONT));
                cf.hwndOwner   = hWndOwner;
                cf.hDC         = IntPtr.Zero;
                cf.lpLogFont   = logFontPtr;
                cf.Flags       = Options | NativeMethods.CF_INITTOLOGFONTSTRUCT | NativeMethods.CF_ENABLEHOOK;
                if (minSize > 0 || maxSize > 0)
                {
                    cf.Flags |= NativeMethods.CF_LIMITSIZE;
                }

                //if ShowColor=true then try to draw the sample text in color,
                //if ShowEffects=false then we will draw the sample text in standard control text color regardless.
                //(limitation of windows control)
                //
                if (ShowColor || ShowEffects)
                {
                    cf.rgbColors = ColorTranslator.ToWin32(color);
                }
                else
                {
                    cf.rgbColors = ColorTranslator.ToWin32(SystemColors.ControlText);
                }

                cf.lpfnHook  = hookProcPtr;
                cf.hInstance = UnsafeNativeMethods.GetModuleHandle(null);
                cf.nSizeMin  = minSize;
                if (maxSize == 0)
                {
                    cf.nSizeMax = int.MaxValue;
                }
                else
                {
                    cf.nSizeMax = maxSize;
                }
                Debug.Assert(cf.nSizeMin <= cf.nSizeMax, "min and max font sizes are the wrong way around");
                if (!SafeNativeMethods.ChooseFont(cf))
                {
                    return(false);
                }


                NativeMethods.LOGFONT lfReturned = null;
                lfReturned = (NativeMethods.LOGFONT)UnsafeNativeMethods.PtrToStructure(logFontPtr, typeof(NativeMethods.LOGFONT));

                if (lfReturned.lfFaceName != null && lfReturned.lfFaceName.Length > 0)
                {
                    lf = lfReturned;
                    UpdateFont(lf);
                    UpdateColor(cf.rgbColors);
                }

                return(true);
            }
            finally {
                if (logFontPtr != IntPtr.Zero)
                {
                    Marshal.FreeCoTaskMem(logFontPtr);
                }
            }
        }
 // returns the value of the corresponding text attribute
 private static object GetStrikethroughStyle(NativeMethods.LOGFONT logfont)
 {
     return(logfont.lfStrikeOut != 0 ? TextDecorationLineStyle.Single : TextDecorationLineStyle.None);
 }