プロセスハンドルをかえすShell関数をつくる2

VBのShell関数は戻り値としてプロセスID(タスクID)をかえします。しかしAPI関数等を使う場合プロセスハンドルが必要となる場合があります。そこでプロセスハンドルをかえすShell関数、ShellExを作ろうと思います。

まずWin32API関数の定義をします。

Private Const STARTF_USESHOWWINDOW = &H1
Private Type STARTUPINFO
    cb As Long
    lpReserved As String
    lpDesktop As String
    lpTitle As String
    dwX As Long
    dwY As Long
    dwXSize As Long
    dwYSize As Long
    dwXCountChars As Long
    dwYCountChars As Long
    dwFillAttribute As Long
    dwFlags As Long
    wShowWindow As Integer
    cbReserved2 As Integer
    lpReserved2 As Long
    hStdInput As Long
    hStdOutput As Long
    hStdError As Long
End Type
Private Type PROCESS_INFORMATION
    hProcess As Long
    hThread As Long
    dwProcessId As Long
    dwThreadId As Long
End Type
Private Declare Function CreateProcess Lib "kernel32" Alias "CreateProcessA" _
    (ByVal lpApplicationName As String, _
    ByVal lpCommandLine As String, _
    ByVal lpProcessAttributes As Long, _
    ByVal lpThreadAttributes As Long, _
    ByVal bInheritHandles As Long, _
    ByVal dwCreationFlags As Long, _
    lpEnvironment As Any, _
    ByVal lpCurrentDriectory As String, _
    lpStartupInfo As STARTUPINFO, _
    lpProcessInformation As PROCESS_INFORMATION) As Long

つぎにShellEx関数を作ります。

Public Function ShellEx(FileName As String , optional Style As Long = vbMinimizedFocus) As Long
  Dim SI As STARTUPINFO
  Dim PI As PROCESS_INFORMATION
  Dim lngRC As Long

  With SI
    .cb = Len(SI)
    .dwFlags = STARTF_USESHOWWINDOW
    .wShowWindow = Style
  End With

  lngRC = CreateProcess(vbNullString, FileName & vbNullString, 0, 0, False, 0, 0, vbNullString, SI, PI)

  If lngRC <> 0 Then ShellEx = PI.hProcess

End Function

使い方はShell関数と同様です。

使用例

Dim lngHandle as Long
lngHandle=ShellEx("Notepad.exe" , vbNormalFocus)
MsgBox "プロセスハンドルは" & lngHandle & "です"

 

戻る