BLOG.CSHARPHELPER.COM: Set another application's size and position in C#
Set another application's size and position in C#
While writing books, there is usually a maximum size that a screen shot can be. I wrote this program to make it easy to set an example program to exactly that size.
This program uses the FindWindow API function to find the target window and the SetWindowPos API function to size and position it. The following code shows how the program defines those functions. It also defines the SetWindowPosFlags enumeration used by SetWindowPos.
This program doesn't set any flags but I've included them here in case you need them. If you don't want them, you could define the last parameter in SetWindowPos to be of type uint and then just pass in 0.
When you click the Go button, the program executes the following code.
// Size and position the application.
private void btnGo_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;
}
// Set the window's position.
int width = int.Parse(txtWidth.Text);
int height = int.Parse(txtHeight.Text);
int x = int.Parse(txtX.Text);
int y = int.Parse(txtY.Text);
SetWindowPos(target_hwnd, IntPtr.Zero, x, y, width, height, 0);
}
The program uses FindWindow to find the target application's handle. This only works if you enter the target application's window title exactly.
Next the program uses SetWindowPos to set the target's size and position. This can have some odd side effects if the window's size mode doesn't match its size. For example, if the window is maximized and you set its size to something smaller than the screen, then the title bar looks a bit messed up around the edges.
Also be careful not to move a window entirely off the screen or you will need to use this program again to get it back.
Comments