Controlling Window State Of Other Applications using C#

One of my friend wanted to control the window state of some application using a c# code. That's why I am writing this article. This also includes Win32 functions.

To start with include namespaces

  1. using System.Runtime.InteropServices; 

  2. using System.Diagnostics;

Now declare these variables

private const int SW_HIDE = 0;

private const int SW_RESTORE = 9;

private int hWnd;

Now declare win32 function ShowWindow

[DllImport("User32")]
private static extern int ShowWindow(int hwnd, int nCmdShow);

The above function accepts 2 parameters hWnd is handle of a window whose window state we want to modify nCmdShow contains integer value which denotes state

Following table will clear it

Sr No nCmdShow Value
1 Hide 0
2 Minimized 1
3 Maximized 2
4 Restore 9

Now the main problem is how to get handle of a particular window. Its simple, suppose you want to get handle of notepad application which is running on your machine then use following code

Process[] p = Process.GetProcessesByName("notepad");

This will return array of all the notepad processes. After this you can use foreach loop to iterate through each process in this array. Here we will just consider first process in array.

The following line of code will return me handle value

hWnd = (int)p[0].MainWindowHandle;

Now if you want to hide this process the just give a call to ShowWindow method as follows

ShowWindow(hWnd, SW_HIDE);

That' it. Notepad will vanish..


Similar Articles