public NativeResourceModule( string filename ) { _moduleHandle = NativeMethods.LoadLibraryEx(filename, IntPtr.Zero, NativeMethods.LOAD_LIBRARY_AS_DATAFILE); if( _moduleHandle.IsInvalid ) { throw new FileNotFoundException("Unable to find native resource module", filename); } }
public void DumpWevtTemplateResource(IntPtr moduleHandle) { if (moduleHandle == IntPtr.Zero) { throw new ArgumentNullException(nameof(moduleHandle)); } using var module = new SafeModuleHandle(moduleHandle, false); using var stream = module.OpenResource("WEVT_TEMPLATE", 1); DumpWevtTemplate(stream); }
private bool LoadStringRes(SafeModuleHandle module, uint resId, out object value) { if (module.IsInvalid) { value = "<<MUI missing>>"; return(false); } value = ResourceUnsafeNativeMethods.LoadString(module, resId); return(true); }
/// <summary> /// Load the library at the given path. /// </summary> public static SafeModuleHandle LoadLibrary(string path, LoadLibraryFlags flags) { SafeModuleHandle handle = Direct.LoadLibraryExW(path, IntPtr.Zero, flags); if (handle.IsInvalid) { throw ErrorHelper.GetIoExceptionForLastError(path); } return(handle); }
/// <summary> /// Gets the file name (path) for the given module handle in the given process. /// </summary> /// <param name="process">The process for the given module or null for the current process.</param> /// <remarks>External process handles must be opened with PROCESS_QUERY_INFORMATION|PROCESS_VM_READ</remarks> public static string GetModuleFileName(SafeModuleHandle module, SafeProcessHandle process = null) { if (process == null) { return(BufferHelper.CachedTruncatingApiInvoke((buffer) => Direct.GetModuleFileNameW(module, buffer, buffer.CharCapacity))); } else { return(BufferHelper.CachedTruncatingApiInvoke((buffer) => Direct.K32GetModuleFileNameExW(process, module, buffer, buffer.CharCapacity))); } }
/// <summary> /// Loads the specified DLL library. /// </summary> /// <param name="fileName">Name of the DLL to load.</param> /// <param name="flags">Flags that affect the loading of the library.</param> /// <returns>A handle to the loaded DLL.</returns> private static SafeModuleHandle LoadLibraryEx(string fileName, uint flags) { SafeModuleHandle ret = DoLoadLibraryEx(fileName, IntPtr.Zero, flags); if (ret.IsInvalid) { throw Interop.GetLastWin32Exception(); } return(ret); }
/// <summary> /// Get a delegate for the given native method /// </summary> /// <remarks> /// Here is a sample delegate definition: /// /// [UnmanagedFunctionPointer(CallingConvention.Cdecl)] /// private delegate int DoubleDelegate(int value); /// /// And it's native signature: /// /// extern "C" __declspec (dllexport) int Double(int); /// </remarks> public static DelegateType GetFunctionDelegate <DelegateType>(SafeModuleHandle library, string methodName) { IntPtr method = Direct.GetProcAddress(library, methodName); if (method == IntPtr.Zero) { throw ErrorHelper.GetIoExceptionForLastError(methodName); } return(Marshal.GetDelegateForFunctionPointer <DelegateType>(method)); }
/// <summary> /// Formats the message from the given DLL, having the system allocate the message buffer. /// </summary> /// <param name="flags">The formatting message flags. This must include <see cref="FORMAT_MESSAGE_ALLOCATE_BUFFER"/>, <see cref="FORMAT_MESSAGE_FROM_HMODULE"/>, and <see cref="FORMAT_MESSAGE_IGNORE_INSERTS"/>.</param> /// <param name="dll">The DLL to search for the message definition.</param> /// <param name="code">The code identifying the message to look up.</param> /// <param name="localMemory">On return, contains a handle to a local memory buffer allocated by the system.</param> /// <param name="minimumBufferSize">Minimum size of the buffer local memory buffer to allocate.</param> /// <returns>The number of valid characters in the local memory buffer.</returns> private static uint FormatMessageFromModuleAllocatingBuffer(uint flags, SafeModuleHandle dll, uint code, out SafeLocalMemoryHandle localMemory, uint minimumBufferSize) { uint ret = DoFormatMessageFromModuleAllocatingBuffer(flags, dll, code, 0, out localMemory, minimumBufferSize, IntPtr.Zero); if (ret == 0) { throw Interop.GetLastWin32Exception(); } return(ret); }
private static void InitCOMAccess() { // Register COM interfaces with WCT. This enables WCT to provide wait information if a thread is blocked on a COM call. // Get a handle to OLE32.DLL. You must keep this handle around for the life time for any WCT session. SafeModuleHandle hmodule = LoadLibraryW("ole32.dll"); // Retrieve the function addresses for the COM helper APIs. IntPtr CallStateCallback = GetProcAddress(hmodule, "CoGetCallState"); IntPtr ActivationStateCallback = GetProcAddress(hmodule, "CoGetActivationState"); // Register these functions with WCT. RegisterWaitChainCOMCallback(CallStateCallback, ActivationStateCallback); }
public void DumpMessageTableResource(string moduleFile) { var module = SafeModuleHandle.LoadImageResource(moduleFile); if (module.IsInvalid) { throw new Win32Exception(); } using (module) using (var stream = module.OpenResource(UnsafeNativeMethods.RT_MESSAGETABLE, 1)) DumpMessageTable(stream); }
public void DumpWevtTemplateResource(string moduleFile) { var module = SafeModuleHandle.LoadImageResource(moduleFile); if (module.IsInvalid) { throw new Win32Exception(); } using (module) using (var stream = module.OpenResource("WEVT_TEMPLATE", 1)) DumpWevtTemplate(stream); }
private void _backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { _dialog.StopProgressDialog(); Marshal.ReleaseComObject(_dialog); _dialog = null; if (_currentAnimationModuleHandle != null) { _currentAnimationModuleHandle.Dispose(); _currentAnimationModuleHandle = null; } OnRunWorkerCompleted(new RunWorkerCompletedEventArgs((!e.Cancelled && e.Error == null) ? e.Result : null, e.Error, e.Cancelled)); }
public static ThemeFile LoadTheme(string styleFilePath, bool isHighContrast, string muiFilePath) { SafeModuleHandle muiHandle = SafeModuleHandle.Zero; if (File.Exists(muiFilePath)) { muiHandle = SafeModuleHandle.LoadImageResource(muiFilePath); } var styleHandle = SafeModuleHandle.LoadImageResource(styleFilePath); return(new ThemeFileLoader(styleFilePath, styleHandle, muiHandle, isHighContrast).LoadTheme()); }
private bool LoadImageFileRes(SafeModuleHandle module, uint resId, out object value) { ResInfoHandle resInfo = module.FindResourceEx("IMAGE", (int)resId, 0); if (resInfo.IsInvalid) { value = null; return(false); } value = new ThemeBitmap((int)resId, module, resInfo); return(true); }
public static UnmanagedResourceManager Create(DocumentReference source) { if (!PathHelper.FileExists(source.Path)) { return((UnmanagedResourceManager)null); } SafeModuleHandle module = NativeMethods.LoadLibraryForResourceAccess(source.Path); if (module == null) { return((UnmanagedResourceManager)null); } return(new UnmanagedResourceManager(source, module)); }
public Stream GetThemeStream(int partId, int stateId, int propertyId, SafeModuleHandle instance) { HResult hr = StyleNativeMethods.GetThemeStream(theme, partId, stateId, propertyId, out IntPtr stream, out uint length, instance); if (!Found(hr)) { return(null); } var buffer = new byte[length]; Marshal.Copy(stream, buffer, 0, buffer.Length); return(new MemoryStream(buffer)); }
/// <summary> /// Loads the specified DLL library. /// </summary> /// <param name="fileName">Name of the DLL to load.</param> /// <param name="flags">Flags that affect the loading of the library.</param> /// <returns>A handle to the loaded DLL.</returns> private static SafeModuleHandle LoadLibraryEx(string fileName, uint flags) { Contract.Ensures(Contract.Result <SafeModuleHandle>() != null); Contract.Ensures(!Contract.Result <SafeModuleHandle>().IsInvalid); SafeModuleHandle ret = DoLoadLibraryEx(fileName, IntPtr.Zero, flags); Contract.Assume(ret != null); if (ret.IsInvalid) { throw Interop.GetLastWin32Exception(); } return(ret); }
/// <summary> /// Formats the message from the given DLL, having the system allocate the message buffer. /// </summary> /// <param name="flags">The formatting message flags. This must include <see cref="FORMAT_MESSAGE_ALLOCATE_BUFFER"/>, <see cref="FORMAT_MESSAGE_FROM_HMODULE"/>, and <see cref="FORMAT_MESSAGE_IGNORE_INSERTS"/>.</param> /// <param name="dll">The DLL to search for the message definition. May not be <c>null</c>.</param> /// <param name="code">The code identifying the message to look up.</param> /// <param name="localMemory">On return, contains a handle to a local memory buffer allocated by the system.</param> /// <param name="minimumBufferSize">Minimum size of the buffer local memory buffer to allocate.</param> /// <returns>The number of valid characters in the local memory buffer.</returns> private static uint FormatMessageFromModuleAllocatingBuffer(uint flags, SafeModuleHandle dll, uint code, out SafeLocalMemoryHandle localMemory, uint minimumBufferSize) { Contract.Requires(dll != null); Contract.Ensures(Contract.ValueAtReturn <SafeLocalMemoryHandle>(out localMemory) != null); Contract.Ensures(Contract.Result <uint>() != 0); uint ret = DoFormatMessageFromModuleAllocatingBuffer(flags, dll, code, 0, out localMemory, minimumBufferSize, IntPtr.Zero); if (ret == 0) { throw Interop.GetLastWin32Exception(); } Contract.Assume(localMemory != null); return(ret); }
/// <summary> /// Gets info for the given module in the given process. /// </summary> /// <param name="process">The process for the given module or null for the current process.</param> /// <remarks>External process handles must be opened with PROCESS_QUERY_INFORMATION|PROCESS_VM_READ</remarks> public static MODULEINFO GetModuleInfo(SafeModuleHandle module, SafeProcessHandle process = null) { if (process == null) { process = ProcessMethods.GetCurrentProcess(); } MODULEINFO info; if (!Direct.K32GetModuleInformation(process, module, out info, (uint)Marshal.SizeOf <MODULEINFO>())) { throw ErrorHelper.GetIoExceptionForLastError(); } return(info); }
private bool LoadRectRes(SafeModuleHandle module, uint resId, out object value) { if (module.IsInvalid) { value = "<<MUI missing>>"; return(false); } string str = ResourceUnsafeNativeMethods.LoadString(module, resId); if (TryParseRectSpec(str, out RECT rect)) { value = rect; return(true); } value = null; return(false); }
public unsafe Stream GetThemeStream( int partId, int stateId, int propertyId, SafeModuleHandle instance) { HResult hr = UxThemeExNativeMethods.UxGetThemeStream( themeFile, theme, partId, stateId, propertyId, out IntPtr stream, out uint length, instance); if (!Found(hr) || stream == IntPtr.Zero) { return(null); } var buffer = new byte[length]; if (length > 0) { Marshal.Copy(stream, buffer, 0, buffer.Length); } return(new UnmanagedMemoryStream( (byte *)stream.ToPointer(), 0, length, FileAccess.Read)); }
/// <summary> /// Extracts the raw data of the resource from the module. /// </summary> /// <param name="hModule">The module handle.</param> /// <param name="resrouceName">The name of the resource.</param> /// <param name="resourceType">The type of the resource.</param> /// <returns>The resource raw data.</returns> private static byte[] GetResourceData(SafeModuleHandle hModule, ResourceName resourceName, ResourceTypes resourceType) { //Find the resource in the module. IntPtr hResInfo = IntPtr.Zero; try { hResInfo = DllImports.FindResource(hModule, resourceName.Value, resourceType); } finally { resourceName.Free(); } if (hResInfo == IntPtr.Zero) { throw new Win32Exception(); } //Load the resource. IntPtr hResData = DllImports.LoadResource(hModule, hResInfo); if (hResData == IntPtr.Zero) { throw new Win32Exception(); } //Lock the resource to read data. IntPtr hGlobal = DllImports.LockResource(hResData); if (hGlobal == IntPtr.Zero) { throw new Win32Exception(); } //Get the resource size. int resSize = DllImports.SizeofResource(hModule, hResInfo); if (resSize == 0) { throw new Win32Exception(); } //Allocate the requested size. byte[] buf = new byte[resSize]; //Copy the resource data into our buffer. Marshal.Copy(hGlobal, buf, 0, buf.Length); return(buf); }
public static IconExtractor Open(string fileName) { if (fileName == null) { throw new ArgumentNullException("fileName"); } if (fileName.Length == 0) { throw new ArgumentException(null, "fileName"); } fileName = Path.GetFullPath(fileName); fileName = Environment.ExpandEnvironmentVariables(fileName); SafeModuleHandle moduleHandle = DllImports.LoadLibraryEx(fileName, IntPtr.Zero, LoadLibraryExFlags.LOAD_LIBRARY_AS_DATAFILE); if (moduleHandle.IsInvalid) { throw Win32Marshal.GetExceptionForLastWin32Error(fileName); } List <ResourceName> iconNames = new List <ResourceName>(); DllImports.EnumResourceNames(moduleHandle, ResourceTypes.RT_GROUP_ICON, (hModule, lpszType, lpszName, lParam) => { if (lpszType == ResourceTypes.RT_GROUP_ICON) { iconNames.Add(new ResourceName(lpszName)); } return(true); }, IntPtr.Zero); return(new IconExtractor(moduleHandle, iconNames)); }
private bool LoadBoolRes(SafeModuleHandle module, uint resId, out object value) { if (module.IsInvalid) { value = "<<MUI missing>>"; return(false); } string str = ResourceUnsafeNativeMethods.LoadString(module, resId); if (str == "1" || string.Equals(str, "true", StringComparison.OrdinalIgnoreCase)) { value = true; return(true); } if (str == "0" || string.Equals(str, "false", StringComparison.OrdinalIgnoreCase)) { value = false; return(true); } value = null; return(true); }
private void RunProgressDialog(IntPtr owner, object argument) { if (_backgroundWorker.IsBusy) { throw new InvalidOperationException(Properties.Resources.ProgressDialogRunning); } if (Animation != null) { try { _currentAnimationModuleHandle = Animation.LoadLibrary(); } catch (Win32Exception ex) { throw new InvalidOperationException(string.Format(System.Globalization.CultureInfo.CurrentCulture, Properties.Resources.AnimationLoadErrorFormat, ex.Message), ex); } catch (System.IO.FileNotFoundException ex) { throw new InvalidOperationException(string.Format(System.Globalization.CultureInfo.CurrentCulture, Properties.Resources.AnimationLoadErrorFormat, ex.Message), ex); } } _cancellationPending = false; _dialog = new Interop.ProgressDialog(); _dialog.SetTitle(WindowTitle); if (Animation != null) { _dialog.SetAnimation(_currentAnimationModuleHandle, (ushort)Animation.ResourceId); } if (CancellationText.Length > 0) { _dialog.SetCancelMsg(CancellationText, null); } _dialog.SetLine(1, Text, UseCompactPathsForText, IntPtr.Zero); _dialog.SetLine(2, Description, UseCompactPathsForDescription, IntPtr.Zero); ProgressDialogFlags flags = ProgressDialogFlags.Normal; if (owner != IntPtr.Zero) { flags |= ProgressDialogFlags.Modal; } switch (ProgressBarStyle) { case Enumerations.ProgressBarStyle.None: flags |= ProgressDialogFlags.NoProgressBar; break; case Enumerations.ProgressBarStyle.MarqueeProgressBar: if (NativeMethods.IsWindowsVistaOrLater) { flags |= ProgressDialogFlags.MarqueeProgress; } else { flags |= ProgressDialogFlags.NoProgressBar; // Older than Vista doesn't support marquee. } break; } if (ShowTimeRemaining) { flags |= ProgressDialogFlags.AutoTime; } if (!ShowCancelButton) { flags |= ProgressDialogFlags.NoCancel; } if (!MinimizeBox) { flags |= ProgressDialogFlags.NoMinimize; } _dialog.StartProgressDialog(owner, null, flags, IntPtr.Zero); _backgroundWorker.RunWorkerAsync(argument); }
private static extern uint DoFormatMessageFromModuleAllocatingBuffer(uint flags, SafeModuleHandle lpSource, uint dwMessageId, uint dwLanguageId, out SafeLocalMemoryHandle lpBuffer, uint nSize, IntPtr arguments);
private static extern IntPtr GetProcAddress(SafeModuleHandle hmodule, String functionName);
public static extern IntPtr FindResource(SafeModuleHandle moduleHandle, int resourceId, string resourceType);
public Win32Resources(string module) { _moduleHandle = NativeMethods.LoadLibraryEx(module, IntPtr.Zero, NativeMethods.LoadLibraryExFlags.LoadLibraryAsDatafile); if( _moduleHandle.IsInvalid ) throw new System.ComponentModel.Win32Exception(System.Runtime.InteropServices.Marshal.GetLastWin32Error()); }
public static extern int LoadString(SafeModuleHandle hInstance, uint uID, StringBuilder lpBuffer, int nBufferMax);
public static extern IntPtr LoadResource(SafeModuleHandle moduleHandle, IntPtr hResInfo);
public static ImageSource LoadIcon(SafeModuleHandle module, string resourceIdentifier, int preferredWidth = 0, int preferredHeight = 0) { return(NativeMethods.LoadIcon(module, resourceIdentifier, preferredWidth, preferredHeight)); }
public static extern int SizeofResource(SafeModuleHandle moduleHandle, IntPtr hResInfo);
internal static extern int LoadString(SafeModuleHandle hInstance, uint uID, StringBuilder lpBuffer, int nBufferMax);
public static extern IntPtr GetProcAddress(SafeModuleHandle hmod, String name);
public ThemeBitmap(int imageId, SafeModuleHandle module, ResInfoHandle resource) { this.module = module; this.resource = resource; ImageId = imageId; }
[DllImport("kernel32.dll")] //, CharSet=CharSet.Unicode public static extern IntPtr GetProcAddress(SafeModuleHandle hmod, String name);
private UnmanagedResourceManager(DocumentReference source, SafeModuleHandle module) { this.Source = source; this.module = module; }