gpt4 book ai didi

c# - 如何从Windows中使用C#删除字体?

转载 作者:行者123 更新时间:2023-12-03 11:14:28 24 4
gpt4 key购买 nike

我正在努力使这种方法起作用。

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.'

该字体已正确从注册表中卸载/注销。

是否有解决方法可以从此目录中删除/清除已卸载/未注册的字体?

最佳答案

尝试将字体文件路径更改为用户目录,并尝试设置字体的path变量。

关于c# - 如何从Windows中使用C#删除字体?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60002195/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com