FontDialog 是 Windows Forms 組件,運行在服務器進程中,會在服務器桌面彈出對話框,客戶端瀏覽器完全無法看到!
此方案僅適用於:
Web 頁面字體選擇必須使用前端 JavaScript 組件(如 Google Fonts API、fontpicker 插件)
項目右鍵 → 添加引用 → .NET 標簽頁 → 勾選 System.Windows.Forms
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();
}
@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 組件 + CSS | FontDialog (服務器彈窗) |
| 服務器生成圖片/PDF 應用字體 | System.Drawing / SkiaSharp + 字體文件 | FontDialog 選擇後傳名稱 |
| WinForms 混合部署內部工具 | FontDialog 可用 | - |
Web 開發中字體選擇屬於前端展示層職責,切勿嘗試在服務器端調用桌面組件,架構分層清晰才能構建可擴展系統。