Invoking windows task manager with 'performance' tab selected - c#

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.

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.

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.

Unfortunately, taskmgr.exe does not support any command line argument.
When run, it will always activate the tab that was active on last close.

Starting with Windows 10 build 18305, you can now set a preferred tab to have Task Manager open to by default.
To update:
Click on the start menu and in the search box type 'Windows Update'
Chose 'Windows Update Settings'
In the left panel click 'Preview Builds'
Click on the 'Check' now.
Download the new build.
After update, change dword value of StartUpTab in Win registry key:
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\TaskManager
0 – Processes tab
1 – Performance tab
2 – App history tab
3 – Startup tab
4 – Users tab
5 – Details tab
6 – Services tab
Win CMD:
reg add HKCU\Software\Microsoft\Windows\CurrentVersion\TaskManager /v "startup" /t REG_DWORD /d "1"
This (experimental) feature is only available to some Windows Insiders.
No other tabs except "Start-up" are supported for older builds of Win 10:
taskmgr /4 /startup
To reset:
reg delete HKCU\Software\Microsoft\Windows\CurrentVersion\TaskManager /v "Preferences" /f
To confirm modified key:
REG ADD "HKCU\Software\Microsoft\Windows\CurrentVersion\Applets\Regedit" /v "LastKey" /d "HKCU\Software\Microsoft\Windows\CurrentVersion\TaskManager" /f & regedit
Tested in Win 10 CMD

Related

Start another application on top most in tablet mode

When I run another .exe from my application it starts in the background and does not show the application on top of the screen instead shows tablet mode home screen , it's working fine in normal desktop mode but when I run it in Windows 10 Tablet mode then it does not show on top it starts in the background.
I've used myWindow.TopMost = true; , but it does not work as intended in Windows 10 Tablet Mode.
Code used to start exe file
Process p = new Process();
p.StartInfo.RedirectStandardOutput= true;
p.RedirectStandardInput = true;
p = Process.Start("myApp.exe");
p.WaitForExit();
the exe I'm invoking(starting) is my own exe application(it's not system app), I'm running app on windows 10.
It's only not working on top in Tablet mode( and I'm targeting my application only for Tablets).
Any help is appreciated..!
As I faced a similar situation, (it is not tablet, or windows-10 related. Has similarities only by WPF and TopMost tags) I'll show you how I resolve it:
I would like to have the FilterWindow always TopMost (but only over my application, not over entire set of apps in my Operating System)
See my code. May it'll helps you.
private void OnFilter() {
var filterViewModel = ViewModelLocator.FilterViewModel;
/* ... */
var filterWindow = new FilterWindow {
DataContext = filterViewModel,
Owner = GetParentWindow()
};
filterWindow.ShowDialog();
SelectedIndex = 0;
}
private static Window GetParentWindow() {
Window parent = null;
var activeWindows = Application.Current.Windows.Cast<Window>().Where(item => (item).IsActive).ToList();
if (activeWindows.Any()) {
parent = activeWindows[activeWindows.Count - 1];
}
else {
foreach (var item in
Application.Current.Windows.Cast<object>().Where(item => item.GetType().Name == typeof(RibbonWindow).Name)) {
parent = item as Window;
}
}
return parent;
}
The magic is Owner = GetParentWindow().
Without setting the Owner the FilterWindow had a ridiculous behavior.
Hope it helps you. If no, I will remove the response. (it does not fit in a comment)
Moerfi's solution of using Owner = GetParentWindow() worked surperb, much thanks for this solution. It also solved another problem I had.
I am writing an application for Surface 3 that runs on Windows 10 Pro on tablet mode, whenever a MessageBox or custom dialog control box is closed, as opposed to going back to parent window, Win 10 goes to start menu.
As if once the dialog control is opened the parent window is being placed into background, so when dialog control is closed there is no active window for Win 10 to switch back.
Setting owner on child dialog control solved that problem. Thank you very much.

Creating sub context menu items in the registry

I need my app to create right-click context menu items (and sub-menu items). I'm not concerned with the code - but I don't know how to make sub-menu items in the registry. It's not as logical as one would expect.
I've searched countless times already and have officially given up searching for now.
I know that we can create a context menu item using regedit.exe by going to the shell key and adding a new one but how do I create sub menu items like 7zip for example?
Take a look at this Code-Project article: Add a context menu to the Windows Explorer. It seems to be very easy by using the Registry class provided by the .net framework.
Some more advanced/better solution seems to be using some library such as: SharpShell
EDIT
Please take a look at: .NET Shell Extensions - Adding submenus to Shell .
Ths part should solve your problem:
// <summary>
// Creates the context menu when the selected item is a folder.
// </summary>
protected void MenuDirectory()
{
ToolStripMenuItem MainMenu;
MainMenu = new ToolStripMenuItem
{
Text = "MenuDirectory",
Image = Properties.Resources.Folder_icon
};
ToolStripMenuItem SubMenu1;
SubMenu1 = new ToolStripMenuItem
{
Text = "DirSubMenu1",
Image = Properties.Resources.Folder_icon
};
var SubMenu2 = new ToolStripMenuItem
{
Text = "DirSubMenu2",
Image = Properties.Resources.Folder_icon
};
SubMenu2.DropDownItems.Clear();
SubMenu2.Click += (sender, args) => ShowItemName();
var SubSubMenu1 = new ToolStripMenuItem
{
Text = "DirSubSubMenu1",
Image = Properties.Resources.Folder_icon
};
SubSubMenu1.Click += (sender, args) => ShowItemName();
// Let's attach the submenus to the main menu
SubMenu1.DropDownItems.Add(SubSubMenu1);
MainMenu.DropDownItems.Add(SubMenu1);
MainMenu.DropDownItems.Add(SubMenu2);
menu.Items.Clear();
menu.Items.Add(MainMenu);
}
You have to create a command folder for example Archive, with two commands: A and B.
Windows Registry Editor Version 5.00
[HKEY_CLASSES_ROOT\*\shell\Archive]
"MUIVerb"="Archive"
"SubCommands"="Windows.A;Windows.B"
The * in key means this menu shows up at right click on any file. If you want it only at the *.7z files, use HKEY_CLASSES_ROOT\.7z\shell\Archive. The value of MUIVerb will be the name of menu item. If you named the MUIVerb to 7-Zip, the right click menu will contains two 7-Zip items.
Then create the commands there:
Windows Registry Editor Version 5.00
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\CommandStore\shell\Windows.A]
"MUIVerb"="Command name of A"
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\CommandStore\shell\Windows.A\command]
#="notepad.exe \"%1\""
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\CommandStore\shell\Windows.B]
"MUIVerb"="Command name of B"
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\CommandStore\shell\Windows.B\command]
#="notepad.exe \"%1\""
In this example, you get an Archive menuitem, with cascaded two command, whats open the current file with notepad. It works with Windows 7 and newer.

Close one tab in chrome using C#

I can close all tab in chrome by use process thus:
Process[] chromeInstances = Process.GetProcessesByName("chrome");
if (chromeInstances.Length > 0)
{
foreach (Process p in chromeInstances)
{
p.Kill(); ;
}
}
But I want close one tab in chrome. It is possible?
According to this post, it is not possible: https://superuser.com/a/306715/68020
You can't close a tab by killing the process. The process represents a renderer that the main browser uses the execute and draw a page, which it then copies to the screen. The "Aw, Snap!" is what the browser displays when the renderer responsible for that tab crashes or is killed. The proper way to close the tab would ideally be via a command-line switch, but there is none that I know of at this time.
Also, as the comment describes,
there isn't a 1:1 relationship between tabs and renderer processes in the first place.

How to force Selenium to ignore ctrl/shift actions made in other application?

I have a test where many 'click on link' actions are proceed for several minutes.
The problem lies here:
- during the tests I click many times on different links,
- test run in background, webdriver window has no focus
- I use other app in that time (text or code editor) and when I press shift/ctrl button there Webdriver captures it and opens the link in new window/tab.
The Webdriver perform click+shift (or click+ctrl) action really unexpectedly. My test fails because of this. Webdriver multiplies the windows and tabs and losing the handle/contex after some time.
Is there any way to prevent Webdriver from capturing the ctrl/shift keys pressed in other application?
More info & code sample
The very simple way to trigger this issue... Code in C#:
for (int i = 0; i < 20; i++)
{
driver.Navigate().GoToUrl("google.com");
driver.FindElement(By.Id("gbqfq")).Clear();
driver.FindElement(By.Id("gbqfq")).SendKeys("were you naughty or nice this year");
driver.FindElement(By.Id("gbqfq")).SendKeys(Keys.Enter);
System.Threading.Thread.Sleep(500);
driver.FindElementByClassName("r").Click();
System.Threading.Thread.Sleep(500);
}
While the test is running:
open a Notepad
press and hold Shift key
after a while you should notice that Webdriver opens new window
if you press and hold Ctrl button it opens new tab
issue occurs also if you minimize the Webdriver window - it still captures the keyboard actions
When you use modifierkeys (Shift, Ctrl) they are not released automatically: the key stays pressed in the background.
To solve this, you can sent Keys.Null to the application, this will release the modifierkeys.

How do I make a tray-icon-only C# application in MonoMac (no dock icon)?

I am trying to create an application that will have a tray icon only, and not appear in the taskbar. (similar to Dropbox) I need to create both Windows and Mac version of the application, so I tried using MonoMac to create the Mac front-end.
What is the best way to create a tray-only application in MonoMac?
All the resources I have found say to do one of two things:
Add <key>LSUIElement</key><string>1</string> to the Info.plist file.
Add the following code to the FinishedLaunching event in the AppDelegate class: NSApplication.SharedApplication.ActivationPolicy = NSApplicationActivationPolicy.Accessory;
I have tried all combinations of these two, but it seems that as soon as I try to instantiate a C# System.Timers.Timer, the icon reappears in the dock at the bottom of the screen. Am I missing something about how OSX handles background applications?
What am I doing wrong? Is there a better way to make a background application that has an upper tray icon but no bottom dock icon in OSX?
(This is very similar to this SO question, but that question was from a couple years ago and was never fully answered, so I'm hoping there might be a more complete answer out there.)
Here's the code I have so far:
public partial class AppDelegate : NSApplicationDelegate
{
MyServiceObject currentServiceObject;
public AppDelegate () { }
public override void FinishedLaunching (NSObject notification)
{
// Construct menu that will be displayed when tray icon is clicked
var notifyMenu = new NSMenu();
var exitMenuItem = new NSMenuItem("Quit My Application",
(a,b) => { System.Environment.Exit(0); }); // Just add 'Quit' command
notifyMenu.AddItem(exitMenuItem);
// Display tray icon in upper-right-hand corner of the screen
var sItem = NSStatusBar.SystemStatusBar.CreateStatusItem(30);
sItem.Menu = notifyMenu;
sItem.Image = NSImage.FromStream(System.IO.File.OpenRead(
NSBundle.MainBundle.ResourcePath + #"/notify-icon.icns"));
sItem.HighlightMode = true;
// Remove the system tray icon from upper-right hand corner of the screen
// (works without adjusting the LSUIElement setting in Info.plist)
NSApplication.SharedApplication.ActivationPolicy =
NSApplicationActivationPolicy.Accessory;
// Start running the program -- If I comment out then no dock icon appears
currentServiceObject = new MyServiceObject();
}
}
I found the problem, and it wasn't related to the application settings at all. Evidently, there are some operations that MacOS does not allow an 'Agent applications' to perform. As soon as one of those methods is called, the application is forced to appear in the dock. The code that was tripping up my application was a call to:
System.Windows.Forms.Cursor.Position.ToString()
Removing that line, and replacing it with the following MonoMac method allowed the application to remain hidden:
NSEvent.CurrentMouseLocation.ToString()
I was able to get this working by setting the value of "Application is agent (UIElement)" key to 1 in the info.plist file. Even though it should be a BOOL value, MonoDevelop makes it a string, but setting it to 1 seems to work. You can also set an empty string the for the "Icon file" but it's not necessary.

Categories