Я на пути к тому, чтобы этот метод заработал.
using Microsoft.Win32;
using System;
using System.Drawing;
using System.Drawing.Text;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
public static class FontManager
{
[DllImport("user32.dll")]
public static extern int SendMessage(int hWnd, uint Msg, int wParam, int lParam);
[DllImport("gdi32.dll", EntryPoint = "RemoveFontResourceW", SetLastError = true)]
public static extern int RemoveFontResource([In][MarshalAs(UnmanagedType.LPWStr)] string lpFileName);
/// <summary>
/// Uninstall a font from the system.
/// </summary>
/// <param name="fontFile">The absolute path of the font.</param>
public static void Uninstall(string fontFile)
{
var targetFontFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), Path.GetFileName(fontFile));
if (File.Exists(targetFontFile))
{
// Get the font name.
PrivateFontCollection fontCollection = new PrivateFontCollection();
fontCollection.AddFontFile(targetFontFile);
var actualFontName = fontCollection.Families[0].Name;
// Remove the font from the registry.
var key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion\Fonts", writable: true);
if (key.GetValueNames().Contains(actualFontName))
{
key.DeleteValue(actualFontName);
}
key.Close();
// Remove the font from the system.
RemoveFontResource(targetFontFile);
// Remove the font file from the fonts directory.
File.SetAttributes(targetFontFile, FileAttributes.Normal);
File.Delete(targetFontFile);
// Broadcast a message that the fonts has changed.
const int WM_FONTCHANGE = 0x001D;
const int HWND_BROADCAST = 0xffff;
SendMessage(HWND_BROADCAST, WM_FONTCHANGE, 0, 0);
}
}
}
Однако я не могу удалить шрифт из каталога Fonts.
// Remove the font file from the fonts directory.
File.SetAttributes(targetFontFile, FileAttributes.Normal);
File.Delete(targetFontFile);
Я получаю это исключение:
System.UnauthorizedAccessException: 'Access to the path 'C:\Windows\Fonts\JetBrainsMono-Bold.ttf' is denied.'
Шрифт правильно удален / незарегистрирован в реестре.
Возможно, есть обходной путь для удаления / очистки удалить / незарегистрированные шрифты из этого каталога?