/// <summary> /// Retrieves information about a range of pages within the virtual address space of a specified process. /// </summary> /// <param name="processHandle">A handle to the process whose memory information is queried.</param> /// <param name="addressFrom">A pointer to the starting address of the region of pages to be queried.</param> /// <param name="addressTo">A pointer to the ending address of the region of pages to be queried.</param> /// <returns>A collection of <see cref="MemoryBasicInformation"/> structures.</returns> public static IEnumerable <MemoryBasicInformation> Query(SafeMemoryHandle processHandle, IntPtr addressFrom, IntPtr addressTo) { // Check if the handle is valid HandleManipulator.ValidateAsArgument(processHandle, "processHandle"); // The first address must be lower than the second if (addressFrom.IsGreaterOrEqualThan(addressTo)) { throw new ArgumentException("The starting address must be lower than the ending address.", "addressFrom"); } // Create the variable storing the result of the call of VirtualQueryEx int ret; // Enumerate the memory pages do { // Allocate the structure to store information of memory MemoryBasicInformation memoryInfo; // Get the next memory page ret = NativeMethods.VirtualQueryEx(processHandle, addressFrom, out memoryInfo, MarshalType <MemoryBasicInformation> .SizeAsPointer); // Increment the starting address with the size of the page addressFrom = addressFrom.Add(memoryInfo.RegionSize); // Return the memory page if (memoryInfo.State != MemoryStateFlags.Free) { yield return(memoryInfo); } } while (addressFrom.IsSmallerThan(addressTo) && ret != 0); }
public static int GetWindowThreadId(IntPtr windowHandle) { HandleManipulator.ValidateAsArgument(windowHandle, "windowHandle"); int trash; return(User32.GetWindowThreadProcessId(windowHandle, out trash)); }
/// <summary> /// Flashes the specified window one time. It does not change the active state of the window. /// To flash the window a specified number of times, use the <see cref="FlashWindowEx(IntPtr, FlashWindowFlags, uint, TimeSpan)"/> function. /// </summary> /// <param name="windowHandle">A handle to the window to be flashed. The window can be either open or minimized.</param> /// <returns> /// The return value specifies the window's state before the call to the <see cref="FlashWindow"/> function. /// If the window caption was drawn as active before the call, the return value is nonzero. Otherwise, the return value is zero. /// </returns> public static bool FlashWindow(IntPtr windowHandle) { // Check if the handle is valid HandleManipulator.ValidateAsArgument(windowHandle, "windowHandle"); // Flash the window return(NativeMethods.FlashWindow(windowHandle, true)); }
/// <summary> /// Sets the specified window's show state. /// </summary> /// <param name="windowHandle">A handle to the window.</param> /// <param name="state">Controls how the window is to be shown.</param> /// <returns>If the window was previously visible, the return value is <c>true</c>, otherwise the return value is <c>false</c>.</returns> public static bool ShowWindow(IntPtr windowHandle, WindowStates state) { // Check if the handle is valid HandleManipulator.ValidateAsArgument(windowHandle, "windowHandle"); // Change the state of the window return(NativeMethods.ShowWindow(windowHandle, state)); }
/// <summary> /// Sends the specified message to a window or windows. /// The SendMessage function calls the window procedure for the specified window and does not return until the window procedure has processed the message. /// </summary> /// <param name="windowHandle">A handle to the window whose window procedure will receive the message.</param> /// <param name="message">The message to be sent.</param> /// <param name="wParam">Additional message-specific information.</param> /// <param name="lParam">Additional message-specific information.</param> /// <returns>The return value specifies the result of the message processing; it depends on the message sent.</returns> public static IntPtr SendMessage(IntPtr windowHandle, uint message, UIntPtr wParam, IntPtr lParam) { // Check if the handle is valid HandleManipulator.ValidateAsArgument(windowHandle, "windowHandle"); // Send the message return(NativeMethods.SendMessage(windowHandle, message, wParam, lParam)); }
public static void SetWindowText(IntPtr windowHandle, string title) { HandleManipulator.ValidateAsArgument(windowHandle, "windowHandle"); if (!User32.SetWindowText(windowHandle, title)) { throw new Win32Exception("Couldn't set the text of the window's title bar."); } }
public static void PostMessage(IntPtr windowHandle, int message, UIntPtr wParam, UIntPtr lParam) { HandleManipulator.ValidateAsArgument(windowHandle, "windowHandle"); if (!User32.PostMessage(windowHandle, message, wParam, lParam)) { throw new Win32Exception($"Couldn't post the message '{message}'."); } }
/// <summary> /// Retrieves the identifier of the thread that created the specified window. /// </summary> /// <param name="windowHandle">A handle to the window.</param> /// <returns>The return value is the identifier of the thread that created the window.</returns> public static int GetWindowThreadId(IntPtr windowHandle) { // Check if the handle is valid HandleManipulator.ValidateAsArgument(windowHandle, "windowHandle"); // Get the thread id int trash; return(NativeMethods.GetWindowThreadProcessId(windowHandle, out trash)); }
/// <summary> /// Closes an open object handle. /// </summary> /// <param name="handle">A valid handle to an open object.</param> public static void CloseHandle(IntPtr handle) { // Check if the handle is valid HandleManipulator.ValidateAsArgument(handle, "handle"); // Close the handle if (!NativeMethods.CloseHandle(handle)) { throw new Win32Exception(string.Format("Couldn't close he handle 0x{0}.", handle)); } }
/// <summary> /// Places (posts) a message in the message queue associated with the thread that created the specified window and returns without waiting for the thread to process the message. /// </summary> /// <param name="windowHandle">A handle to the window whose window procedure is to receive the message. The following values have special meanings.</param> /// <param name="message">The message to be posted.</param> /// <param name="wParam">Additional message-specific information.</param> /// <param name="lParam">Additional message-specific information.</param> public static void PostMessage(IntPtr windowHandle, uint message, UIntPtr wParam, UIntPtr lParam) { // Check if the handle is valid HandleManipulator.ValidateAsArgument(windowHandle, "windowHandle"); // Post the message if (!NativeMethods.PostMessage(windowHandle, message, wParam, lParam)) { throw new Win32Exception(string.Format("Couldn't post the message '{0}'.", message)); } }
/// <summary> /// Sets the text of the specified window's title bar. /// </summary> /// <param name="windowHandle">A handle to the window whose text is to be changed.</param> /// <param name="title">The new title text.</param> public static void SetWindowText(IntPtr windowHandle, string title) { // Check if the handle is valid HandleManipulator.ValidateAsArgument(windowHandle, "windowHandle"); // Set the text of the window's title bar if (!NativeMethods.SetWindowText(windowHandle, title)) { throw new Win32Exception("Couldn't set the text of the window's title bar."); } }
/// <summary> /// Sets the context for the specified thread. /// </summary> /// <param name="threadHandle">A handle to the thread whose context is to be set.</param> /// <param name="context"> /// A pointer to a <see cref="ThreadContext" /> structure that contains the context to be set in the /// specified thread. /// </param> public static void SetThreadContext(SafeMemoryHandle threadHandle, ThreadContext context) { // Check if the handle is valid HandleManipulator.ValidateAsArgument(threadHandle, "threadHandle"); // Set the thread context if (!NativeMethods.SetThreadContext(threadHandle, ref context)) { throw new Win32Exception("Couldn't set the thread context."); } }
public static void SetWindowPlacement(IntPtr windowHandle, int left, int top, int height, int width) { HandleManipulator.ValidateAsArgument(windowHandle, "windowHandle"); var placement = GetWindowPlacement(windowHandle); placement.NormalPosition.Left = left; placement.NormalPosition.Top = top; placement.NormalPosition.Height = height; placement.NormalPosition.Width = width; SetWindowPlacement(windowHandle, placement); }
public static string GetClassName(IntPtr windowHandle) { HandleManipulator.ValidateAsArgument(windowHandle, "windowHandle"); var stringBuilder = new StringBuilder(char.MaxValue); if (User32.GetClassName(windowHandle, stringBuilder, stringBuilder.Capacity) == 0) { throw new Win32Exception("Couldn't get the class name of the window or the window has no class name."); } return(stringBuilder.ToString()); }
/// <summary> /// Releases a region of memory within the virtual address space of a specified process. /// </summary> /// <param name="processHandle">A handle to a process.</param> /// <param name="address">A pointer to the starting address of the region of memory to be freed.</param> public static void Free(SafeMemoryHandle processHandle, IntPtr address) { // Check if the handles are valid HandleManipulator.ValidateAsArgument(processHandle, "processHandle"); HandleManipulator.ValidateAsArgument(address, "address"); // Free the memory if (!NativeMethods.VirtualFreeEx(processHandle, address, 0, MemoryReleaseFlags.Release)) { // If the memory wasn't correctly freed, throws an exception throw new Win32Exception(string.Format("The memory page 0x{0} cannot be freed.", address.ToString("X"))); } }
public static void SetWindowPlacement(IntPtr windowHandle, WindowPlacement placement) { HandleManipulator.ValidateAsArgument(windowHandle, "windowHandle"); if (Debugger.IsAttached && placement.ShowCmd == WindowStates.ShowNormal) { placement.ShowCmd = WindowStates.Restore; } if (!User32.SetWindowPlacement(windowHandle, ref placement)) { throw new Win32Exception("Couldn't set the window placement."); } }
/// <summary> /// Terminates a thread. /// </summary> /// <param name="threadHandle">A handle to the thread to be terminated.</param> /// <param name="exitCode">The exit code for the thread.</param> public static void TerminateThread(SafeMemoryHandle threadHandle, int exitCode) { // Check if the handle is valid HandleManipulator.ValidateAsArgument(threadHandle, "threadHandle"); // Terminate the thread var ret = NativeMethods.TerminateThread(threadHandle, exitCode); // If the function failed if (!ret) { throw new Win32Exception("Couldn't terminate the thread."); } }
public static void FlashWindowEx(IntPtr windowHandle, FlashWindowFlags flags, int count, TimeSpan timeout) { HandleManipulator.ValidateAsArgument(windowHandle, "windowHandle"); var flashInfo = new FlashInfo { Size = Marshal.SizeOf(typeof(FlashInfo)), Hwnd = windowHandle, Flags = flags, Count = count, Timeout = Convert.ToInt32(timeout.TotalMilliseconds) }; User32.FlashWindowEx(ref flashInfo); }
public static WindowPlacement GetWindowPlacement(IntPtr windowHandle) { HandleManipulator.ValidateAsArgument(windowHandle, "windowHandle"); WindowPlacement placement; placement.Length = Marshal.SizeOf(typeof(WindowPlacement)); if (!User32.GetWindowPlacement(windowHandle, out placement)) { throw new Win32Exception("Couldn't get the window placement."); } return(placement); }
public static void SetForegroundWindow(IntPtr windowHandle) { HandleManipulator.ValidateAsArgument(windowHandle, "windowHandle"); if (GetForegroundWindow() == windowHandle) { return; } ShowWindow(windowHandle, WindowStates.Restore); if (!User32.SetForegroundWindow(windowHandle)) { throw new ApplicationException("Couldn't set the window to foreground."); } }
/// <summary> /// Waits until the specified object is in the signaled state or the time-out interval elapses. /// </summary> /// <param name="handle">A handle to the object.</param> /// <param name="timeout">The time-out interval. If this parameter is NULL, the function does not enter a wait state if the object is not signaled; it always returns immediately.</param> /// <returns>Indicates the <see cref="WaitValues"/> event that caused the function to return.</returns> public static WaitValues WaitForSingleObject(SafeMemoryHandle handle, TimeSpan?timeout) { // Check if the handle is valid HandleManipulator.ValidateAsArgument(handle, "handle"); // Wait for single object var ret = NativeMethods.WaitForSingleObject(handle, timeout.HasValue ? Convert.ToUInt32(timeout.Value.TotalMilliseconds) : 0); // If the function failed if (ret == WaitValues.Failed) { throw new Win32Exception("The WaitForSingleObject function call failed."); } return(ret); }
/// <summary> /// Waits an infinite amount of time for the specified object to become signaled. /// </summary> /// <param name="handle">A handle to the object.</param> /// <returns>If the function succeeds, the return value indicates the event that caused the function to return.</returns> public static WaitValues WaitForSingleObject(SafeMemoryHandle handle) { // Check if the handle is valid HandleManipulator.ValidateAsArgument(handle, "handle"); // Wait for single object var ret = NativeMethods.WaitForSingleObject(handle, 0xFFFFFFFF); // If the function failed if (ret == WaitValues.Failed) { throw new Win32Exception("The WaitForSingleObject function call failed."); } return(ret); }
/// <summary> /// Retrieves the context of the specified thread. /// </summary> /// <typeparam name="TContext">The type of the context to dump. /// The type must be unmanaged, so it can be fixed while the native call is done. /// The performance is increased if the structure is blittable, which is the case for the structures /// provided with the library.</typeparam> /// <param name="threadHandle">A handle to the thread whose context is to be retrieved.</param> /// <param name="context">An instance of the structure where the context is loaded into.</param> /// <exception cref="Win32Exception">The context cannot be retrieved from the thread.</exception> public static unsafe void GetThreadContext <TContext>(SafeMemoryHandle threadHandle, ref TContext context) where TContext : unmanaged { // Check if the handle is valid HandleManipulator.ValidateAsArgument(threadHandle, "threadHandle"); // Get the pointer of the structure and pin it, so the GC does not move it fixed(void *contextPtr = &context) { // Get the thread context if (NativeMethods.GetThreadContext(threadHandle, contextPtr) == (void *)0) { throw new Win32Exception("The context cannot be retrieved from the thread."); } } }
/// <summary> /// Suspends the specified thread. /// </summary> /// <param name="threadHandle">A handle to the thread that is to be suspended.</param> /// <returns>The thread's previous suspend count.</returns> public static uint SuspendThread(SafeMemoryHandle threadHandle) { // Check if the handle is valid HandleManipulator.ValidateAsArgument(threadHandle, "threadHandle"); // Suspend the thread var ret = NativeMethods.SuspendThread(threadHandle); // If the function failed if (ret == uint.MaxValue) { throw new Win32Exception("Couldn't suspend the thread."); } return(ret); }
/// <summary> /// Retrieves a descriptor table entry for the specified selector and thread. /// </summary> /// <param name="threadHandle">A handle to the thread containing the specified selector.</param> /// <param name="selector">The global or local selector value to look up in the thread's descriptor tables.</param> /// <returns>A pointer to an <see cref="LdtEntry" /> structure that receives a copy of the descriptor table entry.</returns> public static LdtEntry GetThreadSelectorEntry(SafeMemoryHandle threadHandle, uint selector) { // Check if the handle is valid HandleManipulator.ValidateAsArgument(threadHandle, "threadHandle"); // Get the selector entry LdtEntry entry; if (NativeMethods.GetThreadSelectorEntry(threadHandle, selector, out entry)) { return(entry); } // Else couldn't get the selector entry, throws an exception throw new Win32Exception($"Couldn't get the selector entry for this selector: {selector}."); }
/// <summary> /// Sets the current position and size of the specified window. /// </summary> /// <param name="windowHandle">A handle to the window.</param> /// <param name="left">The x-coordinate of the upper-left corner of the window.</param> /// <param name="top">The y-coordinate of the upper-left corner of the window.</param> /// <param name="height">The height of the window.</param> /// <param name="width">The width of the window.</param> public static void SetWindowPlacement(IntPtr windowHandle, int left, int top, int height, int width) { // Check if the handle is valid HandleManipulator.ValidateAsArgument(windowHandle, "windowHandle"); // Get a WindowPlacement structure of the current window var placement = GetWindowPlacement(windowHandle); // Set the values placement.NormalPosition.Left = left; placement.NormalPosition.Top = top; placement.NormalPosition.Height = height; placement.NormalPosition.Width = width; // Set the window placement SetWindowPlacement(windowHandle, placement); }
/// <summary> /// Sets the show state and the restored, minimized, and maximized positions of the specified window. /// </summary> /// <param name="windowHandle">A handle to the window.</param> /// <param name="placement">A pointer to the <see cref="WindowPlacement"/> structure that specifies the new show state and window positions.</param> public static void SetWindowPlacement(IntPtr windowHandle, WindowPlacement placement) { // Check if the handle is valid HandleManipulator.ValidateAsArgument(windowHandle, "windowHandle"); // If the debugger is attached and the state of the window is ShowDefault, there's an issue where the window disappears if (Debugger.IsAttached && placement.ShowCmd == WindowStates.ShowNormal) { placement.ShowCmd = WindowStates.Restore; } // Set the window placement if (!NativeMethods.SetWindowPlacement(windowHandle, ref placement)) { throw new Win32Exception("Couldn't set the window placement."); } }
/// <summary> /// Flashes the specified window. It does not change the active state of the window. /// </summary> /// <param name="windowHandle">A handle to the window to be flashed. The window can be either opened or minimized.</param> /// <param name="flags">The flash status.</param> /// <param name="count">The number of times to flash the window.</param> /// <param name="timeout">The rate at which the window is to be flashed.</param> public static void FlashWindowEx(IntPtr windowHandle, FlashWindowFlags flags, uint count, TimeSpan timeout) { // Check if the handle is valid HandleManipulator.ValidateAsArgument(windowHandle, "windowHandle"); // Create the data structure var flashInfo = new FlashInfo { Size = Marshal.SizeOf(typeof(FlashInfo)), Hwnd = windowHandle, Flags = flags, Count = count, Timeout = Convert.ToInt32(timeout.TotalMilliseconds) }; // Flash the window NativeMethods.FlashWindowEx(ref flashInfo); }
/// <summary> /// Retrieves the show state and the restored, minimized, and maximized positions of the specified window. /// </summary> /// <param name="windowHandle">A handle to the window.</param> /// <returns>The return value is a <see cref="WindowPlacement"/> structure that receives the show state and position information.</returns> public static WindowPlacement GetWindowPlacement(IntPtr windowHandle) { // Check if the handle is valid HandleManipulator.ValidateAsArgument(windowHandle, "windowHandle"); // Allocate a WindowPlacement structure WindowPlacement placement; placement.Length = Marshal.SizeOf(typeof(WindowPlacement)); // Get the window placement if (!NativeMethods.GetWindowPlacement(windowHandle, out placement)) { throw new Win32Exception("Couldn't get the window placement."); } return(placement); }
/// <summary> /// Reserves a region of memory within the virtual address space of a specified process. /// </summary> /// <param name="processHandle">The handle to a process.</param> /// <param name="size">The size of the region of memory to allocate, in bytes.</param> /// <param name="protectionFlags">The memory protection for the region of pages to be allocated.</param> /// <param name="allocationFlags">The type of memory allocation.</param> /// <returns>The base address of the allocated region.</returns> public static IntPtr Allocate(SafeMemoryHandle processHandle, int size, MemoryProtectionFlags protectionFlags = MemoryProtectionFlags.ExecuteReadWrite, MemoryAllocationFlags allocationFlags = MemoryAllocationFlags.Commit) { // Check if the handle is valid HandleManipulator.ValidateAsArgument(processHandle, "processHandle"); // Allocate a memory page var ret = NativeMethods.VirtualAllocEx(processHandle, IntPtr.Zero, size, allocationFlags, protectionFlags); // Check whether the memory page is valid if (ret != IntPtr.Zero) { return(ret); } // If the pointer isn't valid, throws an exception throw new Win32Exception(string.Format("Couldn't allocate memory of {0} byte(s).", size)); }