Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call windows function (getting the font directory)

Tags:

go

winapi

I try to find out the font folder on a windows installation. AFAICS the proposed way is to call SHGetKnownFolderPath in Shell32.dll with KNOWNFOLDERID set to FOLDERID_Fonts.

I have no idea what to pass to the Call function in the code below:

package main

import (
    "syscall"
)

func main() {
    // HRESULT SHGetKnownFolderPath(
    //   _In_      REFKNOWNFOLDERID rfid,
    //   _In_      DWORD dwFlags,
    //   _In_opt_  HANDLE hToken,
    //   _Out_     PWSTR *ppszPath
    // );

    var (
        shell32             = syscall.NewLazyDLL("Shell32.dll")
        shGetKnowFolderPath = shell32.NewProc("SHGetKnownFolderPath")

        // Doesn't work, of course:
        folderId int
        flags    int
        handle   int
        retval   int
    )

    shGetKnowFolderPath.Call(uintptr(folderId), uintptr(flags), uintptr(handle), uintptr(retval))
}

Any idea? (I guess a workaround for now would be to stick to %windir%\Fonts, but I'd like to get a proper solution).

References:

  • http://msdn.microsoft.com/en-us/library/windows/desktop/bb762181(v=vs.85).aspx
  • http://msdn.microsoft.com/en-us/library/windows/desktop/dd378457(v=vs.85).aspx
like image 392
topskip Avatar asked Jul 30 '13 11:07

topskip


1 Answers

For example,

package main

import (
    "fmt"
    "syscall"
    "unsafe"
)

type GUID struct {
    Data1 uint32
    Data2 uint16
    Data3 uint16
    Data4 [8]byte
}

var (
    FOLDERID_Fonts = GUID{0xFD228CB7, 0xAE11, 0x4AE3, [8]byte{0x86, 0x4C, 0x16, 0xF3, 0x91, 0x0A, 0xB8, 0xFE}}
)

var (
    modShell32               = syscall.NewLazyDLL("Shell32.dll")
    modOle32                 = syscall.NewLazyDLL("Ole32.dll")
    procSHGetKnownFolderPath = modShell32.NewProc("SHGetKnownFolderPath")
    procCoTaskMemFree        = modOle32.NewProc("CoTaskMemFree")
)

func SHGetKnownFolderPath(rfid *GUID, dwFlags uint32, hToken syscall.Handle, pszPath *uintptr) (retval error) {
    r0, _, _ := syscall.Syscall6(procSHGetKnownFolderPath.Addr(), 4, uintptr(unsafe.Pointer(rfid)), uintptr(dwFlags), uintptr(hToken), uintptr(unsafe.Pointer(pszPath)), 0, 0)
    if r0 != 0 {
        retval = syscall.Errno(r0)
    }
    return
}

func CoTaskMemFree(pv uintptr) {
    syscall.Syscall(procCoTaskMemFree.Addr(), 1, uintptr(pv), 0, 0)
    return
}

func FontFolder() (string, error) {
    var path uintptr
    err := SHGetKnownFolderPath(&FOLDERID_Fonts, 0, 0, &path)
    if err != nil {
        return "", err
    }
    defer CoTaskMemFree(path)
    folder := syscall.UTF16ToString((*[1 << 16]uint16)(unsafe.Pointer(path))[:])
    return folder, nil
}

func main() {
    folder, err := FontFolder()
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println("Font Folder:", folder)
}

Output:

Font Folder: C:\Windows\Fonts
like image 115
peterSO Avatar answered Sep 17 '22 09:09

peterSO