Windows フォルダ、Systemフォルダをエクスプローラで開く方法

◆概要

このページは、Visual Basic 6.0でWindows フォルダ、Systemフォルダをエクスプローラで開く方法について記載しています。


Windowフォルダを取得するには、API関数GetWindowsDirectory() 、Systemフォルダを取得するにはAPI関数GetSystemDirectory()を使います。

◆Sample code

フォームに2つのコマンドボタン(cmdExecuteWindowFolder、cmdExecuteSystemFolder)を貼り付けます。
フォームモジュールに次のコードを記述します。

Option Explicit

Option Explicit
'定数
Private Const MAX_PATH As Long = 260

'API宣言
Private Declare Function GetWindowsDirectory Lib _
    "kernel32" Alias "GetWindowsDirectoryA" ( _
    ByVal lpBuffer As String, ByVal nSize As Long _
    ) As Long

Private Declare Function GetSystemDirectory Lib _
    "kernel32" Alias "GetSystemDirectoryA" ( _
    ByVal lpBuffer As String, ByVal nSize As Long _
    ) As Long

Private Sub cmdExecuteSystemFolder_Click()
    'Systemディレクトリの取得
    'ただのStringではいけない
    '必ずバッファのサイズを指定する
    Dim buffer As String * MAX_PATH

    'API呼び出し
    Call GetSystemDirectory(buffer, MAX_PATH)
  
    'C文字列からVB文字列へ変換する
    Dim systemFolder As String

    'vbNullCharの直前までを切り離す
    systemFolder = Left(buffer, InStr(1, buffer, vbNullChar, _
                    vbBinaryCompare) - 1)

    'エクスプローラの起動
    Shell "explorer " & systemFolder, vbNormalFocus

End Sub

Private Sub cmdExecuteWindowFolder_Click()
    'Windowsディレクトリの取得
    'ただのstringではいけない
    '必ずバッファのサイズを指定する
    Dim buffer As String * MAX_PATH

    'API呼び出し
    Call GetWindowsDirectory(buffer, MAX_PATH)

    'C文字列からVB文字列へ変換する
    Dim windowsFolder As String

    'vbNullCharの前までを切り離す
    windowsFolder = Left(buffer, InStr(buffer, vbNullChar) - 1)

    'エキスプローラの起動
    Shell "explorer /E," & windowsFolder, vbNormalFocus

End Sub

Private Sub Form_Load()
    cmdExecuteWindowFolder.Caption = "Windowsディレクトリ"
    cmdExecuteSystemFolder.Caption = "Systemディレクトリ"
    
End Sub



▼ページトップへ