Title: Find a target window and minimize, maximize, or restore it in C#
This is the first in a series of posts that allow one application to manipulate a target window in another application. Note that this isn't something that Microsoft really wants you to do. In general one application should not fiddle around with another application. Because this isn't really approved by Microsoft, there isn't much support for manipulating a target window in another application.
This program finds a target window in another application and minimizes, maximizes, or restores it.
This example uses several API functions and structures. Their definitions are long so I won't include them all here. Download the example to see them. The following lists the API declarations.
static extern IntPtr FindWindowByCaption(IntPtr ZeroOnly,
string lpWindowName);
internal static extern bool GetWindowPlacement(IntPtr hWnd,
out WINDOWPLACEMENT lpwndpl);
static extern bool SetWindowPlacement(IntPtr hWnd,
internal struct WINDOWPLACEMENT
internal enum ShowWindowCommands : int
public struct POINT
public struct RECT
When you click the Set button, the following code executes.
// Set the target's placement.
private void btnSet_Click(object sender, EventArgs e)
{
// Get the target window's handle.
IntPtr target_hwnd =
FindWindowByCaption(IntPtr.Zero, txtAppTitle.Text);
if (target_hwnd == IntPtr.Zero)
{
MessageBox.Show(
"Could not find a window with the title \"" +
txtAppTitle.Text + "\"");
return;
}
// Prepare the WINDOWPLACEMENT structure.
WINDOWPLACEMENT placement = new WINDOWPLACEMENT();
placement.Length = Marshal.SizeOf(placement);
// Get the window's current placement.
GetWindowPlacement(target_hwnd, out placement);
// Set the placement's action.
if (radMaximized.Checked)
placement.ShowCmd = ShowWindowCommands.ShowMaximized;
else if (radMinimized.Checked)
placement.ShowCmd = ShowWindowCommands.ShowMinimized;
else
placement.ShowCmd = ShowWindowCommands.Normal;
// Perform the action.
SetWindowPlacement(target_hwnd, ref placement);
}
The code uses the FindWindowByCaption API function to find the target window. Note that you must enter the target window's caption exactly correctly or FindWindowByCaption won't find it.
Next the code gets the target window's current placement. Before calling GetWindowPlacement (or SetWindowPlacement), the code must save the WINDOWPLACEMENT structure's size in its Length property. The code does that and then calls GetWindowPlacement.
The program leaves all of the WINDOWPLACEMENT fields alone except for the ShowCmd property, which it sets to maximize, minimize, or restore the target.
Finally the code calls SetWindowPlacement to give the target its new state.
Download the example to see additional details.
Download the example to experiment with it and to see additional details.
|