コード例 #1
0
 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);
     }
 }
コード例 #2
0
        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);
        }
コード例 #3
0
        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);
        }
コード例 #4
0
        /// <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);
        }
コード例 #5
0
 /// <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)));
     }
 }
コード例 #6
0
        /// <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);
        }
コード例 #7
0
        /// <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));
        }
コード例 #8
0
        /// <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);
        }
コード例 #9
0
        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);
        }
コード例 #10
0
        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);
        }
コード例 #11
0
        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);
        }
コード例 #12
0
        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));
        }
コード例 #13
0
        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());
        }
コード例 #14
0
        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);
        }
コード例 #15
0
        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));
        }
コード例 #16
0
        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));
        }
コード例 #17
0
        /// <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);
        }
コード例 #18
0
        /// <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);
        }
コード例 #19
0
        /// <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);
        }
コード例 #20
0
        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);
        }
コード例 #21
0
        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));
        }
コード例 #22
0
        /// <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);
        }
コード例 #23
0
        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));
        }
コード例 #24
0
        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);
        }
コード例 #25
0
        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);
        }
コード例 #26
0
 private static extern uint DoFormatMessageFromModuleAllocatingBuffer(uint flags, SafeModuleHandle lpSource, uint dwMessageId, uint dwLanguageId, out SafeLocalMemoryHandle lpBuffer, uint nSize, IntPtr arguments);
コード例 #27
0
 private static extern IntPtr GetProcAddress(SafeModuleHandle hmodule, String functionName);
コード例 #28
0
ファイル: NativeMethods.cs プロジェクト: riverar/devtools
 public static extern IntPtr FindResource(SafeModuleHandle moduleHandle, int resourceId, string resourceType);
コード例 #29
0
 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());
 }
コード例 #30
0
 public static extern int LoadString(SafeModuleHandle hInstance, uint uID, StringBuilder lpBuffer, int nBufferMax);
コード例 #31
0
ファイル: NativeMethods.cs プロジェクト: riverar/devtools
 public static extern IntPtr LoadResource(SafeModuleHandle moduleHandle, IntPtr hResInfo);
コード例 #32
0
ファイル: ResourceHelper.cs プロジェクト: radtek/Shopdrawing
 public static ImageSource LoadIcon(SafeModuleHandle module, string resourceIdentifier, int preferredWidth = 0, int preferredHeight = 0)
 {
     return(NativeMethods.LoadIcon(module, resourceIdentifier, preferredWidth, preferredHeight));
 }
コード例 #33
0
ファイル: NativeMethods.cs プロジェクト: riverar/devtools
 public static extern int SizeofResource(SafeModuleHandle moduleHandle, IntPtr hResInfo);
コード例 #34
0
ファイル: NativeMethods.cs プロジェクト: riverar/devtools
 internal static extern int LoadString(SafeModuleHandle hInstance, uint uID, StringBuilder lpBuffer, int nBufferMax);
コード例 #35
0
ファイル: Kernel32.cs プロジェクト: fearthecowboy/Toolkit
 public static extern IntPtr GetProcAddress(SafeModuleHandle hmod, String name);
コード例 #36
0
 public ThemeBitmap(int imageId, SafeModuleHandle module, ResInfoHandle resource)
 {
     this.module   = module;
     this.resource = resource;
     ImageId       = imageId;
 }
コード例 #37
0
ファイル: Kernel32.cs プロジェクト: zellus/coapp.powershell
 [DllImport("kernel32.dll")] //, CharSet=CharSet.Unicode
 public static extern IntPtr GetProcAddress(SafeModuleHandle hmod, String name);
コード例 #38
0
 private UnmanagedResourceManager(DocumentReference source, SafeModuleHandle module)
 {
     this.Source = source;
     this.module = module;
 }