首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> ASP.NET 基礎 >> ASP.NET 基礎

ASP.NET 調用系統字體對話框 (FontDialog) 實現 Web 字體選擇功能

     編輯:ASP.NET 基礎

⚠️ 關鍵限制聲明

FontDialog 是 Windows Forms 組件,運行在服務器進程中,會在服務器桌面彈出對話框,客戶端瀏覽器完全無法看到!

此方案僅適用於:

  • WinForms 混合部署項目
  • 服務器端批量生成圖片/報表時選擇字體
  • 內部管理工具、桌面應用

Web 頁面字體選擇必須使用前端 JavaScript 組件(如 Google Fonts API、fontpicker 插件)

服務器端調用示例(僅供特定場景參考)

1. 添加引用

項目右鍵 → 添加引用 → .NET 標簽頁 → 勾選 System.Windows.Forms

2. 代碼實現

using System.Windows.Forms;

public void ShowFontDialogDemo()
{
    // 必須在 STA 線程中運行(Windows Forms 要求)
    Thread staThread = new Thread(() =>
    {
        using (FontDialog fontDialog = new FontDialog())
        {
            fontDialog.ShowColor = true;
            fontDialog.ShowEffects = true;
            fontDialog.FontMustExist = true;
            
            if (fontDialog.ShowDialog() == DialogResult.OK)
            {
                Font selectedFont = fontDialog.Font;
                Color selectedColor = fontDialog.Color;
                
                // 應用到服務器端生成的圖片/報表
                // Label1.Font = new Font(selectedFont.FontFamily, selectedFont.Size, selectedFont.Style);
                // Label1.ForeColor = selectedColor;
            }
        }
    });
    
    staThread.SetApartmentState(ApartmentState.STA);
    staThread.Start();
    staThread.Join();
}

正確的 Web 字體選擇方案

方案一:Google Fonts API + 前端選擇器







方案二:fontpicker jQuery 插件



方案三:CSS @font-face 自定義字體

@font-face {
    font-family: 'MyCustomFont';
    src: url('/fonts/MyFont.woff2') format('woff2'),
         url('/fonts/MyFont.woff') format('woff');
    font-weight: normal;
    font-style: normal;
}

.custom-text {
    font-family: 'MyCustomFont', sans-serif;
}

服務器端生成圖片時應用字體 (正確用法)

using System.Drawing;

public byte[] GenerateTextImage(string text, string fontFamily, float fontSize, FontStyle style, Color color)
{
    using (Bitmap bmp = new Bitmap(400, 200))
    using (Graphics g = Graphics.FromImage(bmp))
    {
        g.Clear(Color.White);
        using (Font font = new Font(fontFamily, fontSize, style))
        using (SolidBrush brush = new SolidBrush(color))
        {
            g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAliasGridFit;
            g.DrawString(text, font, brush, new PointF(10, 10));
        }
        
        using (MemoryStream ms = new MemoryStream())
        {
            bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
            return ms.ToArray();
        }
    }
}

總結

場景正確技術棧錯誤嘗試
Web 頁面用戶選擇字體前端 JS 組件 + CSSFontDialog (服務器彈窗)
服務器生成圖片/PDF 應用字體System.Drawing / SkiaSharp + 字體文件FontDialog 選擇後傳名稱
WinForms 混合部署內部工具FontDialog 可用-

Web 開發中字體選擇屬於前端展示層職責,切勿嘗試在服務器端調用桌面組件,架構分層清晰才能構建可擴展系統。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved