问题
I am currently invoking the windows task manager using a click event in WPF. The event simply executes 'Process.Start("taskmgr").
My question is, is there a way to choose which tab inside task manager is selected when the process starts / is displayed? I am looking to have the 'performance' tab selected automatically whenever the click event is raised.
Thanks for the help.
回答1:
To expand on Philipp Schmid's post, I've whipped up a little demo:
Run it as a console application. You need to add references to UIAutomationClient
and UIAutomationTypes
.
One possible improvement you (or I, if you desire) can make is to hide the window initially, only showing it after the correct tab has been selected. I'm not sure if that would work, however, as I'm not sure that AutomationElement.FromHandle
would be able to find a hidden window.
Edit: At least on my computer (Windows 7, 32 bit, .Net framework 4.0), the following code initially creates a hidden Task Manager and shows it after the correct tab has been selected. I don't explicitly show the window after selecting the performance tab, so probably one of the automation lines does as a side-effect.
using System;
using System.Diagnostics;
using System.Windows.Automation;
namespace ConsoleApplication2 {
class Program {
static void Main(string[] args) {
// Kill existing instances
foreach (Process pOld in Process.GetProcessesByName("taskmgr")) {
pOld.Kill();
}
// Create a new instance
Process p = new Process();
p.StartInfo.FileName = "taskmgr";
p.StartInfo.CreateNoWindow = true;
p.Start();
Console.WriteLine("Waiting for handle...");
while (p.MainWindowHandle == IntPtr.Zero) ;
AutomationElement aeDesktop = AutomationElement.RootElement;
AutomationElement aeForm = AutomationElement.FromHandle(p.MainWindowHandle);
Console.WriteLine("Got handle");
// Get the tabs control
AutomationElement aeTabs = aeForm.FindFirst(TreeScope.Children,
new PropertyCondition(AutomationElement.ControlTypeProperty,
ControlType.Tab));
// Get a collection of tab pages
AutomationElementCollection aeTabItems = aeTabs.FindAll(TreeScope.Descendants, new PropertyCondition(AutomationElement.ControlTypeProperty,
ControlType.TabItem));
// Set focus to the performance tab
AutomationElement aePerformanceTab = aeTabItems[3];
aePerformanceTab.SetFocus();
}
}
}
Why do I destroy previous instances of Task Manager? When an instance is already open, secondary instances will open but immediately close. My code doesn't check for this, so the code that finds the window handle will freeze.
回答2:
While taskmgr.exe doesn't have any command line arguments to specify the selected tab, you can use Windows UI Automation to 'navigate' to the performance tab.
回答3:
Unfortunately, taskmgr.exe
does not support any command line argument.
When run, it will always activate the tab that was active on last close.
来源:https://stackoverflow.com/questions/6987130/invoking-windows-task-manager-with-performance-tab-selected