0
0

More than 3 years have passed since last update.

Python3 ctypesでWindowsの特殊フォルダを開く関数のコードと学んだこと

Posted at

Python3でctypesを使ってWindowsの特殊フォルダを開く関数のコードとそれを書く過程で学んだことです。

フォントフォルダを開く
import os
import ctypes
from ctypes import oledll, wintypes


def getshellfolderpath(csidl: int) -> str:
    if not isinstance(csidl, int):
        raise TypeError
    SHGetFolderPathW = oledll.shell32.SHGetFolderPathW
    SHGetFolderPathW.argtypes = [
        wintypes.HWND, ctypes.c_int, wintypes.HANDLE,
        wintypes.DWORD, wintypes.LPWSTR]
    path = ctypes.create_unicode_buffer(wintypes.MAX_PATH)
    SHGetFolderPathW(0, csidl, 0, 0, path)
    return path.value


CSIDL_FONTS = 0x0014
os.startfile(getshellfolderpath(CSIDL_FONTS))

  • Python 3では標準ライブラリのctypesを使ってWin32 APIを操作できる。
  • Win32 APIの一般的な型(HWNDDWORD等)はctypes.wintypesに定義されている。
  • ctypesは動的リンクライブラリのロードのためにcdllpydllwindlloledllをエクスポートする。cdllpydllはcdecl呼び出し規約、windllctypes.oledllはstdcall呼び出し規約。ctypes.oledllは戻り値をHRESULTと仮定して失敗時にOSErrorを送出する。公式ドキュメント
  • WCHAR型のバッファーはctypes.create_unicode_buffer関数で作成する。戻り値のvalueで文字列を取得できる。公式ドキュメント
  • ファイル/フォルダを関連付けで開くにはos.startfile関数が使える。
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0