Archive for 5月 18th, 2012

  1. Hello, COM(VB.NET) World!

    Posted on 5月 18th, 2012 by cx20

    COM(VB.NET)

    COM(Component Object Model)はマイクロソフトの提唱するプログラム部品の仕様である。
    COM を用いて開発された部品であれば言語を問わず利用することができる。
    以下は VB.NET による COM クライアント(事前バインディングならびに実行時バインディング)の例となっている。

    ソースコード(事前バインディング)

    Imports System
    Imports System.Runtime.InteropServices
    Imports Shell32
     
    Module Hello
        Sub Main()
            Dim shell As New Shell
            Dim folder As Folder
            Dim vRootFolder As Object = ShellSpecialFolderConstants.ssfWINDOWS
            folder = shell.BrowseForFolder(0, "Hello, COM(VB.NET) World!", 0, vRootFolder)
            If Not folder Is Nothing Then
                Marshal.ReleaseComObject(folder)
            End If
            Marshal.ReleaseComObject(shell)
        End Sub
    End Module

    コンパイル方法(事前バインディング)

    C:¥> SET PATH=C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin;%PATH%
    C:¥> tlbimp %SystemRoot%\system32\shell32.dll /out:Shell32.dll
    C:¥> vbc /r:Shell32.dll Hello.vb

    ソースコード(実行時バインディング)

    Imports System
    Imports System.Runtime.InteropServices
     
    Module Hello
        Sub Main()
            Dim shell As Object
            Dim folder As Object
            shell = CreateObject("Shell.Application")
            folder = shell.BrowseForFolder(0, "Hello, COM(VB.NET) World!", 0, 36)
            If Not folder Is Nothing Then
                Marshal.ReleaseComObject(folder)
            End If
            Marshal.ReleaseComObject(shell)
        End Sub
    End Module

    コンパイル方法(実行時バインディング)

    C:¥> vbc Hello.vb

    実行結果

    +----------------------------------------+
    |Browse For Folder                    [X]|
    +----------------------------------------+
    | Hello, COM(VB.NET) Wolrd!              |
    |                                        |
    | +------------------------------------+ |
    | |[Windows]                           | |
    | | +[addins]                          | |
    | | +[AppCompat]                       | |
    | | +[AppPatch]                        | |
    | | +[assembly]                        | |
    | |     :                              | |
    | |     :                              | |
    | |     :                              | |
    | +------------------------------------+ |
    | [Make New Folder]    [  OK  ] [Cancel] |
    +----------------------------------------+