Esempio n. 1
0
        /// <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);
        }
Esempio n. 2
0
        public static int GetWindowThreadId(IntPtr windowHandle)
        {
            HandleManipulator.ValidateAsArgument(windowHandle, "windowHandle");
            int trash;

            return(User32.GetWindowThreadProcessId(windowHandle, out trash));
        }
Esempio n. 3
0
 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.");
     }
 }
Esempio n. 4
0
        /// <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));
        }
Esempio n. 5
0
        /// <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));
        }
Esempio n. 6
0
        /// <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));
        }
Esempio n. 7
0
        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}'.");
            }
        }
Esempio n. 8
0
        /// <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));
        }
Esempio n. 9
0
        /// <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.");
            }
        }
Esempio n. 10
0
        /// <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.");
            }
        }
Esempio n. 11
0
        /// <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));
            }
        }
Esempio n. 12
0
        public void HandleToThreadId()
        {
            // Arrange
            var threadHandle = Resources.MemorySharp.Threads.MainThread;

            // Act
            var ret = HandleManipulator.HandleToThreadId(threadHandle.Handle);

            // Assert
            Assert.AreEqual(threadHandle.Id, ret, "The both thread id are equal.");
        }
Esempio n. 13
0
        public void HandleToProcessId()
        {
            // Arrange
            var processHandle = Resources.MemorySharp.Handle;

            // Act
            var ret = HandleManipulator.HandleToProcessId(processHandle);

            // Assert
            Assert.AreEqual(Resources.ProcessTest.Id, ret, "The both process id are not equal.");
        }
Esempio n. 14
0
        /// <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));
            }
        }
Esempio n. 15
0
        /// <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")));
            }
        }
Esempio n. 16
0
        public void CreateRemoteThread()
        {
            // Arrange
            var handle = MemoryCore.OpenProcess(ProcessAccessFlags.AllAccess, Resources.ProcessTest.Id);

            // Act
            var thread   = ThreadCore.CreateRemoteThread(handle, new IntPtr(1), IntPtr.Zero, ThreadCreationFlags.Suspended);
            var threadId = HandleManipulator.HandleToThreadId(thread);

            // Assert
            Assert.IsFalse(thread.IsInvalid);
            Assert.IsTrue(Resources.ProcessTest.Threads.Cast <ProcessThread>().Any(t => t.Id == threadId));
        }
Esempio n. 17
0
        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());
        }
Esempio n. 18
0
        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);
        }
Esempio n. 19
0
        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.");
            }
        }
Esempio n. 20
0
        /// <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.");
            }
        }
Esempio n. 21
0
        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);
        }
Esempio n. 22
0
        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);
        }
Esempio n. 23
0
        /// <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);
        }
Esempio n. 24
0
        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.");
            }
        }
Esempio n. 25
0
        /// <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}.");
        }
Esempio n. 26
0
        /// <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);
        }
Esempio n. 27
0
        /// <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.");
                }
            }
        }
Esempio n. 28
0
        /// <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);
        }
Esempio n. 29
0
        /// <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);
        }
Esempio n. 30
0
        /// <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.");
            }
        }