The program presented here allows you to minimize any open Window to the system tray with just one click. After reading this article you will know how to call unmanaged code from a .NET application using P/Invoke.
All the functionality of this application is achieved using Windows API functions so you should be familiar with basic
winapi programming. Consequently you should know what P/Invoke is and how it works.
P/Invoke or Platform Invoke allows you to call unmanaged functions from managed code. To do that you need to declare a method and specify the name of the DLL file which contains the method using
DllImport attribute. For example here is a declaration needed to call
ShowWindow function from a C# application:
public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
extern keyword is used to indicate that the method is implemented externally. Perhaps the most difficult task with P/Invoke is to know how to substitute unmanaged types with managed types. This is a great website which has lots of
winapi function declarations. There are many tutorials about P/Invoke so I won't go into more details here. See references for the links.
When you run the application it hides the main form and an icon is shown in the system tray. When you right-click the icon a list of all visible Windows is displayed. If you click one of them then that Window will disappear and a new icon will appear in the system tray. The icon is the same as the icon of the executable that launched the Window. Clicking on the icon will bring the Window back. Apart from this there are two commands available to minimize all Windows to tray or to show all minimized Windows. Both commands have hotkeys associated with them and they can be changed from the options Window. To open the options Window just double-click the main icon. Other options include adding the program to the start-up program list and ignoring Windows without a title.
When you right-click the icon a list of all visible Windows appears. To enumerate all Windows you should call
winapi function called
EnumWindows. The function takes two parameters. The first one is a pointer to a callback function. The code snippet below shows how this function works:
private void getwindows()
winapi.EnumWindowsProc callback = new winapi.EnumWindowsProc(enumwindows);
private bool enumwindows(IntPtr hWnd, int lParam)
StringBuilder title = new StringBuilder(256);
winapi.GetWindowText(hWnd, title, 256);
if (string.IsNullOrEmpty(title.ToString())&& set.IgnoreTitle)
if (title.Length != 0 || (title.Length == 0 & hWnd != winapi.statusbar))
windows.Add(new window(hWnd, title.ToString(), winapi.IsIconic(hWnd),
window is a class that has just four fields:
hwnd - to uniquely identify the
title - the tit
le of the
ismaximized store information about the state of the
windows is an instance of the
When a user clicks on one of the Windows we need to hide it.
ShowWindow() API is used to achieve this. Just pass the handle to the Window as a first parameter and
SW_HIDE constant (which is equal to zero) as a second parameter.
private void showwindow(window wnd, bool hide)
winapi.ShowWindow(wnd.handle, state(wnd, hide));
private int state(window wd, bool hide)
The Window is hidden so we need to retrieve the icon of the executable file that created this Window. To achieve this we need to get the path of the executable first. These are the required steps:
- Get the process id that created the specified Window using
- Get a handle of the process by
- Get the executable path by calling
These steps were suggested by Mark Salsbery here: retrieve executable path by hwnd. All these functions are
winapi functions imported by
dllimport attribute. Here is the actual implementation ported to C#.
private string pathfromhwnd(IntPtr hwnd)
winapi.GetWindowThreadProcessId(hwnd, out dwProcessId);
IntPtr hProcess = winapi.OpenProcess(
winapi.ProcessAccessFlags.VMRead | winapi.ProcessAccessFlags.QueryInformation,
StringBuilder path = new StringBuilder(1024);
winapi.GetModuleFileNameEx(hProcess, IntPtr.Zero, path, 1024);
To retrieve the path to the executable file you can also use
GetProcessImageFileName API but it returns a path in device form and works on XP and higher.
GetWindowModuleFileName seemed to be another option but it works only if the specified Window is owned by the calling process.
Now when we have the path to the executable, we can extract the icon that is displayed by explorer using the
SHGetFileInfo() function. You need to pass the path of the executable and an instance of
SHFILEINFO structure that will receive the result. After you have retrieved a handle to the icon you must call
DestoyIcon() API to prevent a memory leak.
private Icon Iconfrompath(string path)
System.Drawing.Icon icon = null;
winapi.SHFILEINFO info = new winapi.SHFILEINFO();
winapi.SHGetFileInfo(path, 0, ref info, (uint)Marshal.SizeOf(info),
winapi.SHGFI_ICON | winapi.SHGFI_SMALLICON);
System.Drawing.Icon temp = System.Drawing.Icon.FromHandle(info.hIcon);
icon = (System.Drawing.Icon)temp.Clone();
At this point we have the necessary icon so we just create and show
NotifyIcon and setup its click event handler. When the click event occurs, the corresponding Window is shown and
NotifyIcon is destroyed.
When an icon is clicked we need to display the corresponding Window. First check if there exists a Window with the specified handle and then call
ShowWindow() again. This time the second parameter depends on the
state of the
window. If the Window was
minimized) while hiding it, it will be shown
void tray_Click(object sender, EventArgs e)
NotifyIcon tray = sender as NotifyIcon;
window wnd = tray.Tag as window;
MessageBox.Show("Window does not exist");
tray.Click -= new EventHandler(tray_Click);
This program allows to customize hotkeys for two commands: 'all to tray' and 'show all'. To add hotkey functionality to your application, first you need to register it.
RegisterHotKey() is a function that is responsible for doing it. It takes four parameters:
- Handle to the
window that will receive
WM_HOTKEY messages generated by the hot key
- ID of the hotkey
- Combination of modifier keys (Alt, Ctrl, Shift etc.)
- The key itself that should be pressed. The code below registers hotkey for 'All to tray' command
if (mod > 0 && key > 0)
winapi.RegisterHotKey(this.Handle, 1729, mod, 64 + key);
To handle the
WM_HOTKEY message generated by the hotkey in a .NET application you should override
WndProc function which processes Windows messages. Don't forget to call
WndProc method of the base class so that other messages get handled.
protected override void WndProc(ref Message m)
private void ProcessHotkey(IntPtr wparam)
if (wparam.ToInt32() == 1729)
if (wparam.ToInt32() == 1730)
When the application exits or hotkey changes we don't need the existing hotkey any more so we should unregister it. It is easier then registering the hotkey and is achieved by calling
UnregisterHotKey() function. Just pass the handle of the
window and ID of the hotkey:
if (mod > 0 && key > 0)
You can add the program to start-up from the options Window. To add program to start-up you need to navigate to HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run key, create a new string and set its value equal to the application's path. Removing the program from start-up is easier: you just remove the value. The code snippet below shows how to do it:
private void startup(bool add)
isinstartup = add;
RegistryKey key = Registry.CurrentUser.OpenSubKey(
key.SetValue("Tray minimizer", "\"" + Application.ExecutablePath + "\"");
If you try to launch the second instance of the application you will get a message box saying that it is already running. This is achieved using
Mutex allows to share resources between threads. When the first instance of the program is launched it creates a new
mutex. When a second instance is launched it checks the existence of the
mutex. If it exists then it exits. When the first instance quits it releases the existing
static void Main()
Mutex mt = null;
mt = Mutex.OpenExisting("Tray minimizer");
if (mt == null)
mt = new Mutex(true, "Tray minimizer");
MessageBox.Show("Application already running");
This application shows how powerful
winapi is and how it can be used from a .NET application to achieve effects that would be otherwise impossible.
- July 2, 2007 - Initial release
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.