Skip to content

Instantly share code, notes, and snippets.

@weltkante
Last active March 15, 2022 16:18
Show Gist options
  • Save weltkante/dd0ed188ab3bb0ba3c0f96a854959818 to your computer and use it in GitHub Desktop.
Save weltkante/dd0ed188ab3bb0ba3c0f96a854959818 to your computer and use it in GitHub Desktop.
Example for Win32 Activat Context to load a regfree COM manifest
[STAThread]
static void Main()
{
ACTCTXW context = new ACTCTXW();
context.cbSize = Marshal.SizeOf<ACTCTXW>();
context.lpSource = "YourManifestFile.manifest";
var handle = Win32.CreateActCtxW(ref context);
if (handle == IntPtr.Zero)
throw new Win32Exception();
try
{
if (!Win32.ActivateActCtx(handle, out var cookie))
throw new Win32Exception();
try
{
// do COM interop
}
finally
{
if (!Win32.DeactivateActCtx(0, cookie))
throw new Win32Exception();
}
}
finally
{
Win32.ReleaseActCtx(handle);
}
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
struct ACTCTXW
{
public int cbSize; // ULONG
public int dwFlags; // DWORD
public string lpSource; // LPCWSTR
public short wProcessorArchitecture; // USHORT
public short wLangId; // LANGID
public string lpAssemblyDirectory; // LPCWSTR
public string lpResourceName; // LPCWSTR
public string lpApplicationName; // LPCWSTR
public IntPtr hModule; // HMODULE
}
static class Win32
{
[DllImport("kernel32", SetLastError = true)]
public static extern IntPtr CreateActCtxW( // WINBASEAPI HANDLE WINAPI
[In] ref ACTCTXW pActCtx); // _In_ PCACTCTXW
[DllImport("kernel32")]
public static extern void ReleaseActCtx( // WINBASEAPI VOID WINAPI
IntPtr hActCtx); // _Inout_ HANDLE
[DllImport("kernel32", SetLastError = true)]
public static extern bool ActivateActCtx( // _Success_(return) WINBASEAPI BOOL WINAPI
IntPtr hActCtx, // _Inout_opt_ HANDLE
out IntPtr lpCookie); // _Out_ ULONG_PTR *
[DllImport("kernel32", SetLastError = true)]
public static extern bool DeactivateActCtx( // _Success_(return) WINBASEAPI BOOL WINAPI
int dwFlags, // _In_ DWORD
IntPtr ulCookie); // _In_ ULONG_PTR
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment