Feedback

C# - Fonts Verzeichnis finden unter Vista oder Windows XP

Veröffentlicht von am 4/10/2008
(1 Bewertungen)
How to get the Fonts directory


someone told me I could use GetEnvironmentVariable like this:
string fontDir = Environment.GetEnvironmentVariable("windir") + @"\Fonts";

the two drawbacks are that it relies on the "windir" to be set (which is usualy the case on a windows system) and it assumes
that the Fonts directory is called "Fonds" and at the default location in the "windir" directory

I think it is better to let the system figure out where the Fonts directory is located ...


using System.Runtime.InteropServices;

...

// for Vista
[DllImport("shell32.dll")]
extern static int SHGetKnownFolderPath(ref Guid rfid, int dwFlags, int
  hToken, out IntPtr path);
[DllImport("ole32.dll")]
extern static void CoTaskMemFree(IntPtr pv);
// for Windows XP
[DllImport("shell32.dll")]
static extern int SHGetFolderPath(IntPtr hwndOwner, int nFolder, IntPtr hToken,
  uint dwFlags, [Out] StringBuilder pszPath);

...

// the routine:
private string GetFontPath()
{

    string result = "";
    if ((System.Environment.OSVersion.Version.Major > 5))
    {
        // You are running Vista

        // In Windows SDK for Vista, you will find all known folders
        // are defined in KnownFolders.h:
        Guid FOLDERID_Fonts = new Guid("{FD228CB7-AE11-4AE3-864C-16F3910AB8FE}"); ;

        IntPtr intPtr;
        SHGetKnownFolderPath(ref FOLDERID_Fonts, 0, 0, out intPtr);

        // convert the IntPtr to a string via Marshal.PtrToStringUni
        result = Marshal.PtrToStringUni(intPtr);
        // free the resource via CoTaskMemFree
        CoTaskMemFree(intPtr);
    }
    else
    {
        // Windows XP

        StringBuilder sb = new StringBuilder();
        SHGetFolderPath(IntPtr.Zero, 0x0014, IntPtr.Zero, 0x0000, sb);//CSIDL_FONTS = 0x0014
        string fontDir = sb.ToString();
        result = fontDir;
    }

    return result;
}

Kommentare zum Snippet

 

Logge dich ein, um hier zu kommentieren!

Ähnliche Snippets