Set Window Action - (Minimize / Maximize)






3.64/5 (25 votes)
Application to minimize / maximize a window.
Introduction
In this article, I am trying to minimize / maximize a running application window.
Using the code
The GetWindowPlacement
, FindWindow
, and SetWindowPlacement
functions from user32.dll are used to manage the window operations.
The FindWindow
function is used to retrieve the handle of the window whose class name and window name match the specified string. This function won't search for the child window (FindWindowEx
is used for the child window).
WINDOWPLACEMENT
The WINDOWPLACEMENT
structure is used to hold information about the placement of the window on the screen. The GetWindowPlacemnt
and SetWindowPlacement
functions are used to set and get the WINDOWPLACEMENT
of the specific window based on the provided handle.
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool GetWindowPlacement(IntPtr hWnd, ref WINDOWPLACEMENT lpwndpl);
[DllImport("user32.dll", SetLastError = true)]
static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
[DllImport("user32.dll")]
static extern bool SetWindowPlacement(IntPtr hWnd,
ref WINDOWPLACEMENT lpwndpl);
private struct POINTAPI
{
public int x;
public int y;
}
private struct RECT
{
public int left;
public int top;
public int right;
public int bottom;
}
private struct WINDOWPLACEMENT
{
public int length;
public int flags;
public int showCmd;
public POINTAPI ptMinPosition;
public POINTAPI ptMaxPosition;
public RECT rcNormalPosition;
}
void WindowAction(string className)
{
System.IntPtr app_hwnd;
WINDOWPLACEMENT wp = new WINDOWPLACEMENT();
app_hwnd = FindWindow(className, null);
GetWindowPlacement(app_hwnd,ref wp);
wp.showCmd = 2; // 1- Normal; 2 - Minimize; 3 - Maximize;
SetWindowPlacement(app_hwnd,ref wp);
}
The WindowAction
function gets the class name (e.g.: Notepad) as a parameter and minimizes it. But, we can avoid using FindWindow
, which is native code, by calling a combination of Process.GetProcessByName
and Process.MainWindowHandle
.
private void minWindow(){
Process[] processes = Process.GetProcessesByName("Notepad");
foreach (Process p in processes)
{
System.IntPtr app_hwnd;
WINDOWPLACEMENT wp = new WINDOWPLACEMENT();
app_hwnd = p.MainWindowHandle;
GetWindowPlacement(app_hwnd, ref wp);
wp.showCmd = 2;
SetWindowPlacement(app_hwnd, ref wp);
}
}
The above snippet is used to minimize the Notepad application using the Process.GetProcessName
function.