Interop

39.1 P/Invoke: Calling Native Windows APIs

Resources: pinvoke.net, the Marshal class, and SafeHandle for native handles.

Imports System.Runtime.InteropServices

Public Module NativeMethods
    ' VB-specific Declare syntax
    Public Declare Auto Function MessageBox Lib "user32.dll" (hWnd As IntPtr, text As String, caption As String, type As UInteger) As Integer

    ' DllImport attribute (same as C#)
    <DllImport("kernel32.dll", SetLastError:=True)>
    Public Function GetTickCount64() As ULong
    End Function

    <DllImport("user32.dll", CharSet:=CharSet.Unicode)>
    Public Function FindWindow(lpClassName As String, lpWindowName As String) As IntPtr
    End Function

    <StructLayout(LayoutKind.Sequential)>
    Public Structure POINT
        Public X As Integer
        Public Y As Integer
    End Structure

    <DllImport("user32.dll")>
    Public Function GetCursorPos(ByRef lpPoint As POINT) As Boolean
    End Function
End Module

MessageBox(IntPtr.Zero, "Hello from Win32", "VB Interop", 0)
Dim pt As POINT
GetCursorPos(pt)
Console.WriteLine($"Mouse at {pt.X}, {pt.Y}")
Console.WriteLine(Marshal.GetLastWin32Error())

39.2 COM Interop

Exposing VB.NET classes to COM (for VBA/VB6 callers): <ComVisible(True)>, <Guid("...")>, <ClassInterface(ClassInterfaceType.AutoDual)>, then register with regasm (.NET Framework) or a COM host (<EnableComHosting> on .NET 5+).

VSTO (Visual Studio Tools for Office): build Excel/Word/Outlook add-ins in VB.NET (.NET Framework). Modern alternative: Office Add-ins (JavaScript).

Server-side Office automation is unsupported by Microsoft. Use ClosedXML, EPPlus, or Open XML SDK libraries instead.

' Early binding: add a COM reference (e.g., Microsoft Excel Object Library) → interop types
Imports Excel = Microsoft.Office.Interop.Excel

Dim app As New Excel.Application With {.Visible = False}
Dim wb As Excel.Workbook = app.Workbooks.Add()
Dim ws As Excel.Worksheet = CType(wb.Sheets(1), Excel.Worksheet)
ws.Range("A1").Value = "Product"
ws.Range("B1").Value = "Price"
ws.Cells(2, 1).Value = "Laptop"
ws.Cells(2, 2).Value = 1200
ws.Range("A1:B1").Font.Bold = True
ws.Columns.AutoFit()
wb.SaveAs("C:\Temp\report.xlsx")
wb.Close()
app.Quit()
Marshal.ReleaseComObject(ws) : Marshal.ReleaseComObject(wb) : Marshal.ReleaseComObject(app)   ' release COM objects

' Late binding (no reference needed, Option Strict Off): Module 32

39.3 Calling C# and Other .NET Languages

Add a project reference or NuGet package. Interop is seamless because everything compiles to IL. Avoid C# features VB can't consume (Module 53).