This is pretty easy to do, every window in Windows has the innate ability to be resizable. It is just turned off for a PictureBox, you can turn it back on by listening for the WM_NCHITTEST message. You simply tell Windows that the cursor is on a corner of a window, you get everything else for free. You’ll also want to draw a grab handle so it is clear to the user that dragging the corner will resize the box.
Add a new class to your project and paste the code shown below. Build + Build. You’ll get a new control on top of the toolbox, drop it on a form. Set the Image property and you’re set to try it.
using System;
using System.Drawing;
using System.Windows.Forms;
class SizeablePictureBox : PictureBox {
public SizeablePictureBox() {
this.ResizeRedraw = true;
}
protected override void OnPaint(PaintEventArgs e) {
base.OnPaint(e);
var rc = new Rectangle(this.ClientSize.Width - grab, this.ClientSize.Height - grab, grab, grab);
ControlPaint.DrawSizeGrip(e.Graphics, this.BackColor, rc);
}
protected override void WndProc(ref Message m) {
base.WndProc(ref m);
if (m.Msg == 0x84) { // Trap WM_NCHITTEST
var pos = this.PointToClient(new Point(m.LParam.ToInt32()));
if (pos.X >= this.ClientSize.Width - grab && pos.Y >= this.ClientSize.Height - grab)
m.Result = new IntPtr(17); // HT_BOTTOMRIGHT
}
}
private const int grab = 16;
}
Another very cheap way to get the resizing for free is by giving the control a resizable border. Which works on all corners and edges. Paste this code into the class (you don’t need WndProc anymore):
protected override CreateParams CreateParams {
get {
var cp = base.CreateParams;
cp.Style |= 0x840000; // Turn on WS_BORDER + WS_THICKFRAME
return cp;
}
}