Grzzlwmpf
Grzzlwmpf

Reputation: 51

C# control 3rd party program in system tray

I'm currently writing a C# program which basically functions as a watchdog for a 3rd party program: If the traffic falls below a certain value, the process is killed and then restarted [using a simple taskkill /im].
This is working perfectly fine, with one exception - if the program is minimized to the system tray, it will not respond to taskkill /im and you have to force-terminate it with taskkill /f /im.

As one can guess, this is by far not the best way to end a program. So I'm currently searching for a way to access the Windows system tray and basically perform a click on the program/call a method to maximize it back to normal.
I had thought about literally simulating a click on the tray, but found this method to be way to inaccurate and unpredictable.
Is there another way to accomplish this [by using a system api, for example]?

Thanks!

Upvotes: 1

Views: 218

Answers (2)

NtFreX
NtFreX

Reputation: 11377

The only way you can iteract with the tray icon of another application in windows is by simulation the mouse click. This has the mayor flaw that if the user is interacting with the mouse at the same time you "steel" hes cursor and he cannot work.

If you know you will not end up with a memory leek (if its a managed app you've won) and the application you are killing isn't doing some important stuff when it's exiting a process kill is the better option.

Upvotes: 0

mammago
mammago

Reputation: 247

You can try using the user32.dll to maximize the processes window.

// Pinvoke declaration for ShowWindow
private const int SW_SHOWMAXIMIZED = 3;

[DllImport("user32.dll")]
static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

// Sample usage
ShowWindow(proc.MainWindowHandle, SW_SHOWMAXIMIZED);

Taken from this SO answer. For a complete list of window states visit this MSDN Page

You can get the WindowHandle by doing something like this

var processes = Process.GetProcessesByName("nameOfYourProcess");

foreach(var process in processes)
{
   var windowHandle = process.getMainWindowHandle;
}

Though this will only work if the process still has a Window.

Upvotes: 1

Related Questions