アプリケーション・プロセスのインスタンスハンドル(HINSTANCE)を取得するには、現在実行しているアセンブリに含まれるモジュールからHINSTANCEを取得する。 モジュールからHINSTANCEを取得するにはMarshal.GetHINSTANCEメソッドを使用する。
using System;
using System.Reflection;
using System.Runtime.InteropServices;
class Sample {
public static IntPtr GetHInstance()
{
// 現在実行しているアセンブリからモジュールを取得
Module mod = Assembly.GetExecutingAssembly().GetModules()[0];
// モジュールのHINSTANCEを取得
return Marshal.GetHINSTANCE(mod);
}
static void Main()
{
IntPtr hInstance = GetHInstance();
Console.WriteLine(hInstance);
}
}
Imports System
Imports System.Reflection
Imports System.Runtime.InteropServices
Class Sample
Public Shared Function GetHInstance() As IntPtr
' 現在実行しているアセンブリからモジュールを取得
Dim m As [Module] = Assembly.GetExecutingAssembly().GetModules()(0)
' モジュールのHINSTANCEを取得
Return Marshal.GetHINSTANCE(m)
End Function
Public Shared Sub Main()
Dim hInstance As IntPtr = GetHInstance()
Console.WriteLine(hInstance)
End Sub
End Class
なお、Visual StudioのデバッグオプションでVisual Studioホスティングプロセスを有効にしている場合は、ホスティングプロセス(*.vshost.exe)のHINSTANCEが取得される(?)ため、HINSTANCEを使ったAPI呼び出し等が失敗する。 これを回避するには、Visual Studioホスティングプロセスを無効にするか、*.vshost.exeではなく直接*.exeを実行する必要がある。