/// <summary> /// Opens a registry key in the Registry Editor. /// </summary> /// <param name="window"> /// The window in which the elevation dialog, if any, should be centered. /// </param> /// <param name="keyName"> /// The path to the registry key, in either abbreviated (HKCU, HKLM, etc.) /// or full (HKEY_CURRENT_USER, etc.) format. /// </param> public static void OpenKeyInRegedit(IWin32Window window, string keyName) { string lastKey = keyName; // Expand the abbreviations. if (lastKey.ToLowerInvariant().StartsWith("hkcu")) { lastKey = "HKEY_CURRENT_USER" + lastKey.Substring(4); } else if (lastKey.ToLowerInvariant().StartsWith("hku")) { lastKey = "HKEY_USERS" + lastKey.Substring(3); } else if (lastKey.ToLowerInvariant().StartsWith("hkcr")) { lastKey = "HKEY_CLASSES_ROOT" + lastKey.Substring(4); } else if (lastKey.ToLowerInvariant().StartsWith("hklm")) { lastKey = "HKEY_LOCAL_MACHINE" + lastKey.Substring(4); } // Set the last opened key in regedit config. Note that if we are on // Vista, we need to append "Computer\" to the beginning. using (var regeditKey = Microsoft.Win32.Registry.CurrentUser.CreateSubKey( @"Software\Microsoft\Windows\CurrentVersion\Applets\Regedit", Microsoft.Win32.RegistryKeyPermissionCheck.ReadWriteSubTree )) { if (OSVersion.IsAboveOrEqual(WindowsVersion.Vista)) { regeditKey.SetValue("LastKey", "Computer\\" + lastKey); } else { regeditKey.SetValue("LastKey", lastKey); } } // If we have UAC and we aren't elevated, request that regedit be elevated // and pass the window handle. This is so that we get the elevation // dialog in the center of the specified window because it looks nice. // Also, this makes sure we don't throw an exception if the user denies // elevation. if (OSVersion.HasUac && Program.ElevationType == TokenElevationType.Limited) { Program.StartProgramAdmin( Environment.SystemDirectory + "\\..\\regedit.exe", "", null, ShowWindowType.Normal, window != null ? window.Handle : IntPtr.Zero ); } else { System.Diagnostics.Process.Start(Environment.SystemDirectory + "\\..\\regedit.exe"); } }
public TerminatorWindow(int PID) { InitializeComponent(); this.AddEscapeToClose(); this.SetTopMost(); _pid = PID; labelProgress.Text = "Double-click a termination method or click Run."; this.AddTest("TP1", "Terminates the process using NtTerminateProcess"); this.AddTest("TP2", "Creates a remote thread in the process which terminates the process"); this.AddTest("TT1", "Terminates the process' threads"); this.AddTest("TT2", "Modifies the process' threads with contexts which terminate the process"); if (OSVersion.IsAboveOrEqual(WindowsVersion.Server2003)) { this.AddTest("TP1a", "Terminates the process using NtTerminateProcess (alternative method)"); this.AddTest("TT1a", "Terminates the process' threads (alternative method)"); } this.AddTest("CH1", "Closes the process' handles"); this.AddTest("W1", "Sends the WM_DESTROY message to the process' windows"); this.AddTest("W2", "Sends the WM_QUIT message to the process' windows"); this.AddTest("TJ1", "Assigns the process to a job object and terminates the job"); this.AddTest("TD1", "Debugs the process and closes the debug object"); this.AddTest("TP3", "Terminates the process in kernel-mode (if possible)"); this.AddTest("TT3", "Terminates the process' threads in kernel-mode (if possible)"); if (KProcessHacker2.Instance != null) { this.AddTest("TT4", "Terminates the process' threads using a dangerous kernel-mode method"); } this.AddTest("M1", "Writes garbage to the process' memory regions"); this.AddTest("M2", "Sets the page protection of the process' memory regions to PAGE_NOACCESS"); }
/// <summary> /// Called by an application's RecoveryCallback method to indicate that the recovery work is complete. /// </summary> /// <remarks> /// This should be the last call made by the RecoveryCallback method because /// Windows Error Reporting will terminate the application after this method is invoked. /// </remarks> /// <param name="success">true to indicate the the program was able to complete its recovery /// work before terminating; otherwise false</param> private static void ApplicationRecoveryFinished(bool success) { if (OSVersion.IsAboveOrEqual(WindowsVersion.Vista)) { AppRestartRecoveryNativeMethods.ApplicationRecoveryFinished(success); } }
private void UpdateInfo() { var basicInfo = _mutantHandle.GetBasicInformation(); labelCurrentCount.Text = basicInfo.CurrentCount.ToString(); labelAbandoned.Text = basicInfo.AbandonedState.ToString(); // Windows Vista and above have owner information. if (OSVersion.IsAboveOrEqual(WindowsVersion.Vista)) { var ownerInfo = _mutantHandle.GetOwnerInformation(); if (ownerInfo.ClientId.ProcessId != 0) { labelOwner.Text = ownerInfo.ClientId.GetName(true); } else { labelOwner.Text = "N/A"; } labelLabelOwner.Visible = true; labelOwner.Visible = true; } else { labelLabelOwner.Visible = false; labelOwner.Visible = false; } }
/// <summary> /// Sets the theme of a control. /// </summary> /// <param name="control">The control to modify.</param> /// <param name="theme">A name of a theme.</param> public static void SetTheme(this Control control, string theme) { // Don't set on XP, doesn't look better than without SetWindowTheme. if (OSVersion.IsAboveOrEqual(WindowsVersion.Vista)) { Win32.SetWindowTheme(control.Handle, theme, null); } }
private const int TVS_EX_FADEINOUTEXPANDOS = 0x0040; //auto hide the +/- signs protected override void OnHandleCreated(System.EventArgs e) { if (OSVersion.IsAboveOrEqual(WindowsVersion.Vista)) { Win32.SendMessage(this.Handle, (WindowMessage)TVM_SETEXTENDEDSTYLE, 0, TVS_EX_FADEINOUTEXPANDOS); ProcessHacker.Common.PhUtils.SetTheme(this, "explorer"); } base.OnHandleCreated(e); }
private const int TVS_EX_FADEINOUTEXPANDOS = 0x0040; //auto hide the +/- signs protected override void OnHandleCreated(System.EventArgs e) { if (OSVersion.IsAboveOrEqual(WindowsVersion.Vista)) { Win32.SendMessage(this.Handle, (WindowMessage)TVM_SETEXTENDEDSTYLE, IntPtr.Zero, (IntPtr)TVS_EX_FADEINOUTEXPANDOS); Win32.SetWindowTheme(this.Handle, "Explorer", null); } base.OnHandleCreated(e); }
private const int TVS_EX_FADEINOUTEXPANDOS = 0x0040; //auto hide the +/- signs protected override void OnHandleCreated(System.EventArgs e) { if (OSVersion.IsAboveOrEqual(WindowsVersion.Vista)) { Win32.SendMessage(this.Handle, (WindowMessage)TVM_SETEXTENDEDSTYLE, 0, TVS_EX_FADEINOUTEXPANDOS); HResult setThemeResult = Win32.SetWindowTheme(this.Handle, "explorer", null); setThemeResult.ThrowIf(); } base.OnHandleCreated(e); }
/// <summary> /// Removes an application's restart registration. /// </summary> private static void UnregisterApplicationRestart() { if (OSVersion.IsAboveOrEqual(WindowsVersion.Vista)) { HResult hr = AppRestartRecoveryNativeMethods.UnregisterApplicationRestart(); if (hr == HResult.Fail) { throw new ExternalException("Unregister for restart failed."); } } }
public static void IsNetworkError(string url, IntPtr hwnd) { if (OSVersion.IsAboveOrEqual(WindowsVersion.Vista)) { IntPtr ndfhandle = IntPtr.Zero; HResult ndfCreate = Win32.NdfCreateWebIncident(url, ref ndfhandle); ndfCreate.ThrowIf(); Win32.NdfExecuteDiagnosis(ndfhandle, hwnd); //Will throw error if user cancels Win32.NdfCloseIncident(ndfhandle); } }
private void TP2() { using (ProcessHandle phandle = new ProcessHandle(_pid, ProcessAccess.CreateThread | ProcessAccess.VmOperation | ProcessAccess.VmWrite)) { if (OSVersion.IsAboveOrEqual(WindowsVersion.Vista)) { // Vista and above export. phandle.CreateThread(Loader.GetProcedure("ntdll.dll", "RtlExitUserProcess"), IntPtr.Zero); } else { phandle.CreateThread(Loader.GetProcedure("kernel32.dll", "ExitProcess"), IntPtr.Zero); } } }
/// <summary> /// Registers an application for automatic restart if the application is terminated by Windows Error Reporting. /// </summary> /// <param name="settings">An object that specifies the command line arguments used to restart the /// application, and the conditions under which the application should not be restarted.</param> /// <remarks>A registered application will not be restarted if it executed for less than 60 seconds before terminating.</remarks> private static void RegisterForApplicationRestart(RestartSettings settings) { if (OSVersion.IsAboveOrEqual(WindowsVersion.Vista)) { HResult hr = AppRestartRecoveryNativeMethods.RegisterApplicationRestart(settings.Command, settings.Restrictions); switch (hr) { case HResult.Fail: throw new InvalidOperationException("Application failed to registered for restart."); case HResult.InvalidArgument: throw new ArgumentException("Failed to register application for restart due to bad parameters."); } } }
private unsafe void OnWmReflectNotify(ref Message m) { NMHDR *hdr = (NMHDR *)m.LParam; if (OSVersion.IsAboveOrEqual(WindowsVersion.Vista) && hdr->code == LVN_LinkClick) { NMLVLINK link = (NMLVLINK)Marshal.PtrToStructure(m.LParam, typeof(NMLVLINK)); this.OnGroupLinkClicked(this.FindGroup(link.SubItemIndex)); } else if (hdr->code == NM_DBLClk) { if (!_doubleClickChecks && this.CheckBoxes) { _doubleClickCheckHackActive = true; } } }
/// <summary> /// Called by an application's RecoveryCallback method /// to indicate that it is still performing recovery work. /// </summary> /// <returns>A Boolean value indicating whether the user canceled the recovery.</returns> private static bool ApplicationRecoveryInProgress() { if (OSVersion.IsAboveOrEqual(WindowsVersion.Vista)) { bool canceled; HResult hr = AppRestartRecoveryNativeMethods.ApplicationRecoveryInProgress(out canceled); if (hr == HResult.Fail) { throw new InvalidOperationException("This method must be called from the registered callback method."); } return(canceled); } return(true); }
void ISupportInitialize.EndInit() { if (!DesignMode) { if (OSVersion.IsAboveOrEqual(WindowsVersion.Vista)) { foreach (DictionaryEntry de in properties) { AddVistaMenuItem((MenuItem)de.Key); } } else // Pre-Vista menus { if (ownerForm != null) { ownerForm.ChangeUICues += ownerForm_ChangeUICues; } foreach (DictionaryEntry de in properties) { AddPreVistaMenuItem((MenuItem)de.Key); } //add event handle for each menu item's measure & draw routines foreach (DictionaryEntry parent in menuParents) { foreach (MenuItem mnuItem in ((Menu)parent.Key).MenuItems) { mnuItem.DrawItem += MenuItem_DrawItem; mnuItem.MeasureItem += MenuItem_MeasureItem; mnuItem.OwnerDraw = true; } } } formHasBeenIntialized = true; } }
/// <summary> /// Registers an application for recovery by Application Restart and Recovery. /// </summary> /// <param name="settings">An object that specifies the callback method, an optional parameter to pass to the callback /// method and a time interval.</param> /// <remarks>The time interval is the period of time within which the recovery callback method calls /// the ApplicationRecoveryInProgress method to indicate that it is still performing recovery work.</remarks> private static void RegisterForApplicationRecovery(RecoverySettings settings) { if (OSVersion.IsAboveOrEqual(WindowsVersion.Vista)) { if (settings == null) { throw new ArgumentNullException("settings"); } GCHandle handle = GCHandle.Alloc(settings.RecoveryData); HResult hr = AppRestartRecoveryNativeMethods.RegisterApplicationRecoveryCallback(AppRestartRecoveryNativeMethods.internalCallback, (IntPtr)handle, settings.PingInterval, (uint)0); switch (hr) { case HResult.InvalidArgument: throw new ArgumentException("Application was not registered for recovery due to bad parameters."); case HResult.Fail: throw new ExternalException("Application failed to register for recovery."); } } }
public void UpdateStatistics() { if (!Program.ProcessProvider.Dictionary.ContainsKey(_pid)) { return; } ProcessItem item = Program.ProcessProvider.Dictionary[_pid]; labelCPUPriority.Text = item.Process.BasePriority.ToString(); labelCPUKernelTime.Text = Utils.FormatTimeSpan(new TimeSpan(item.Process.KernelTime)); labelCPUUserTime.Text = Utils.FormatTimeSpan(new TimeSpan(item.Process.UserTime)); labelCPUTotalTime.Text = Utils.FormatTimeSpan(new TimeSpan(item.Process.KernelTime + item.Process.UserTime)); labelMemoryPB.Text = Utils.FormatSize(item.Process.VirtualMemoryCounters.PrivatePageCount); labelMemoryWS.Text = Utils.FormatSize(item.Process.VirtualMemoryCounters.WorkingSetSize); labelMemoryPWS.Text = Utils.FormatSize(item.Process.VirtualMemoryCounters.PeakWorkingSetSize); labelMemoryVS.Text = Utils.FormatSize(item.Process.VirtualMemoryCounters.VirtualSize); labelMemoryPVS.Text = Utils.FormatSize(item.Process.VirtualMemoryCounters.PeakVirtualSize); labelMemoryPU.Text = Utils.FormatSize(item.Process.VirtualMemoryCounters.PagefileUsage); labelMemoryPPU.Text = Utils.FormatSize(item.Process.VirtualMemoryCounters.PeakPagefileUsage); labelMemoryPF.Text = ((ulong)item.Process.VirtualMemoryCounters.PageFaultCount).ToString("N0"); labelIOReads.Text = item.Process.IoCounters.ReadOperationCount.ToString("N0"); labelIOReadBytes.Text = Utils.FormatSize(item.Process.IoCounters.ReadTransferCount); labelIOWrites.Text = item.Process.IoCounters.WriteOperationCount.ToString("N0"); labelIOWriteBytes.Text = Utils.FormatSize(item.Process.IoCounters.WriteTransferCount); labelIOOther.Text = item.Process.IoCounters.OtherOperationCount.ToString("N0"); labelIOOtherBytes.Text = Utils.FormatSize(item.Process.IoCounters.OtherTransferCount); labelOtherHandles.Text = ((ulong)item.Process.HandleCount).ToString("N0"); if (_pid > 0) { try { labelOtherGDIHandles.Text = item.ProcessQueryHandle.GetGuiResources(false).ToString("N0"); labelOtherUSERHandles.Text = item.ProcessQueryHandle.GetGuiResources(true).ToString("N0"); if (OSVersion.HasCycleTime) { labelCPUCycles.Text = item.ProcessQueryHandle.GetCycleTime().ToString("N0"); } else { labelCPUCycles.Text = "N/A"; } if (OSVersion.IsAboveOrEqual(WindowsVersion.Vista)) { labelMemoryPP.Text = item.ProcessQueryHandle.PagePriority.ToString(); labelIOPriority.Text = item.ProcessQueryHandle.IoPriority.ToString(); } } catch { } } else { labelOtherGDIHandles.Text = "0"; labelOtherUSERHandles.Text = "0"; labelCPUCycles.Text = "0"; labelMemoryPP.Text = "0"; labelIOPriority.Text = "0"; } }
public void SetImage(MenuItem mnuItem, Image value, bool ignorePending) { if (_delaySetImageCalls && !ignorePending) { _pendingSetImageCalls.Enqueue(new KeyValuePair <MenuItem, Image>(mnuItem, value)); return; } Properties prop = EnsurePropertiesExists(mnuItem); if (DesignMode) { prop.Image = value; } if (!DesignMode && OSVersion.IsAboveOrEqual(WindowsVersion.Vista)) { //Destroy old bitmap object if (prop.renderBmpHbitmap != IntPtr.Zero) { DeleteObject(prop.renderBmpHbitmap); prop.renderBmpHbitmap = IntPtr.Zero; } //if there's no Image, then just bail out if (value == null) { // wj32: clean up resources before doing that... RemoveVistaMenuItem(mnuItem); return; } //convert to 32bppPArgb (the 'P' means The red, green, and blue components are premultiplied, according to the alpha component.) Bitmap renderBmp = new Bitmap(value.Width, value.Height, System.Drawing.Imaging.PixelFormat.Format32bppPArgb); Graphics g = Graphics.FromImage(renderBmp); g.DrawImage(value, 0, 0, value.Width, value.Height); g.Dispose(); prop.renderBmpHbitmap = renderBmp.GetHbitmap(Color.FromArgb(0, 0, 0, 0)); renderBmp.Dispose(); if (formHasBeenIntialized) { AddVistaMenuItem(mnuItem); } } else if (!DesignMode && OSVersion.IsBelow(WindowsVersion.Vista)) { if (prop.PreVistaBitmap != null) { prop.PreVistaBitmap.Dispose(); prop.PreVistaBitmap = null; } if (value == null) { RemoveVistaMenuItem(mnuItem); return; } Bitmap bmp = new Bitmap(value.Width, value.Height, System.Drawing.Imaging.PixelFormat.Format32bppPArgb); Graphics g = Graphics.FromImage(bmp); g.DrawImage(value, 0, 0, value.Width, value.Height); g.Dispose(); prop.PreVistaBitmap = bmp; //for every Pre-Vista Windows, add the parent of the menu item to the list of parents if (formHasBeenIntialized) { AddPreVistaMenuItem(mnuItem); } } }
private void unloadMenuItem_Click(object sender, EventArgs e) { if (!PhUtils.ShowConfirmMessage( "Unload", _pid != 4 ? "the selected module" : "the selected driver", _pid != 4 ? "Unloading a module may cause the process to crash." : "Unloading a driver may cause system instability.", true )) { return; } if (_pid == 4) { try { var moduleItem = (ModuleItem)listModules.SelectedItems[0].Tag; string serviceName = null; // Try to find the name of the service key for the driver by // looping through the objects in the Driver directory and // opening each one. using (var dhandle = new DirectoryHandle("\\Driver", DirectoryAccess.Query)) { foreach (var obj in dhandle.GetObjects()) { try { using (var driverHandle = new DriverHandle("\\Driver\\" + obj.Name)) { if (driverHandle.GetBasicInformation().DriverStart == moduleItem.BaseAddress) { serviceName = driverHandle.GetServiceKeyName(); break; } } } catch { } } } // If we didn't find the service name, use the driver base name. if (serviceName == null) { if (moduleItem.Name.ToLower().EndsWith(".sys")) { serviceName = moduleItem.Name.Remove(moduleItem.Name.Length - 4, 4); } else { serviceName = moduleItem.Name; } } RegistryKey servicesKey = Registry.LocalMachine.OpenSubKey("SYSTEM\\CurrentControlSet\\Services", true); bool serviceKeyCreated; RegistryKey serviceKey; // Check if the service key exists so that we don't delete it // later if it does. if (Array.Exists <string>(servicesKey.GetSubKeyNames(), (keyName) => (string.Compare(keyName, serviceName, true) == 0))) { serviceKeyCreated = false; } else { serviceKeyCreated = true; // Create the service key. serviceKey = servicesKey.CreateSubKey(serviceName); serviceKey.SetValue("ErrorControl", 1, RegistryValueKind.DWord); serviceKey.SetValue("ImagePath", "\\??\\" + moduleItem.FileName, RegistryValueKind.ExpandString); serviceKey.SetValue("Start", 1, RegistryValueKind.DWord); serviceKey.SetValue("Type", 1, RegistryValueKind.DWord); serviceKey.Close(); servicesKey.Flush(); } try { Windows.UnloadDriver(serviceName); } finally { if (serviceKeyCreated) { servicesKey.DeleteSubKeyTree(serviceName); } servicesKey.Close(); } listModules.SelectedItems.Clear(); } catch (Exception ex) { MessageBox.Show("Unable to unload the driver. Make sure Process Hacker " + "is running with administrative privileges. Error:\n\n" + ex.Message, "Process Hacker", MessageBoxButtons.OK, MessageBoxIcon.Error); } } else { try { using (ProcessHandle phandle = new ProcessHandle(_pid, Program.MinProcessQueryRights | ProcessAccess.VmOperation | ProcessAccess.VmRead | ProcessAccess.VmWrite | ProcessAccess.CreateThread)) { IntPtr baseAddress = ((ModuleItem)listModules.SelectedItems[0].Tag).BaseAddress; phandle.SetModuleReferenceCount(baseAddress, 1); ThreadHandle thread; if (OSVersion.IsAboveOrEqual(WindowsVersion.Vista)) { // Use RtlCreateUserThread to bypass session boundaries. Since // LdrUnloadDll is a native function we don't need to notify CSR. thread = phandle.CreateThread( Loader.GetProcedure("ntdll.dll", "LdrUnloadDll"), baseAddress ); } else { // On XP it seems we need to notify CSR... thread = phandle.CreateThreadWin32( Loader.GetProcedure("kernel32.dll", "FreeLibrary"), baseAddress ); } thread.Wait(1000 * Win32.TimeMsTo100Ns); NtStatus exitStatus = thread.GetExitStatus(); if (exitStatus == NtStatus.DllNotFound) { if (IntPtr.Size == 8) { PhUtils.ShowError("Unable to find the module to unload. This may be caused " + "by an attempt to unload a mapped file or a 32-bit module."); } else { PhUtils.ShowError("Unable to find the module to unload. This may be caused " + "by an attempt to unload a mapped file."); } } else { exitStatus.ThrowIf(); } thread.Dispose(); } listModules.SelectedItems.Clear(); } catch (Exception ex) { PhUtils.ShowException("Unable to unload the module", ex); } } }
private void CompareHandleBestNameWithFilterString( Dictionary <int, ProcessHandle> processHandles, SystemHandleEntry currhandle, string lowerFilter) { try { // Don't get handles from processes in other session // if we don't have KPH to reduce freezes. Note that // on Windows 7 the hanging bug appears to have been // fixed, so there is an exception for that. if ( KProcessHacker.Instance == null && !OSVersion.IsAboveOrEqual(WindowsVersion.Seven) ) { try { if (isCurrentSessionIdCache.ContainsKey(currhandle.ProcessId)) { if (!isCurrentSessionIdCache[currhandle.ProcessId]) { return; } } else { bool isCurrentSessionId = Win32.GetProcessSessionId(currhandle.ProcessId) == Program.CurrentSessionId; isCurrentSessionIdCache.Add(currhandle.ProcessId, isCurrentSessionId); if (!isCurrentSessionId) { return; } } } catch { return; } } if (!processHandles.ContainsKey(currhandle.ProcessId)) { processHandles.Add(currhandle.ProcessId, new ProcessHandle(currhandle.ProcessId, Program.MinProcessGetHandleInformationRights)); } var info = currhandle.GetHandleInfo(processHandles[currhandle.ProcessId]); if (string.IsNullOrEmpty(info.BestName)) { return; } if (!info.BestName.ToLower().Contains(lowerFilter)) { return; } CallHandleMatchListView(currhandle, info); } catch { return; } }