Friday, June 20, 2008

C# Windows Forms: Enabling users to resize components at run time

This has nothing to do with the topic of this blog. The only way it relates is the C# aspect. I have been surfing for 2 days and could not find the solution to this problem. I am creating a user control, but the user needs to be able to resize it. Go on, search the net, but you'll find rubbish.

The manner in which I solved the problem is very simplistic. I made the control the "background" to the "main" control (can be a panel) which is smaller and offset to the background. That forms a border, so when you click on the background, it allows you to drag resize. Then all you have to do is fit the contents. I'm pretty sure this is how Microsoft does it.

  1. Create the variables you'll need for maintaining:
    //MouseMove is used in conjunction
    private bool _mouseDown;
    //remember the mouse's original point.
    private Point _orig;
    //for storing the mouse difference
    private Point _diff;
    //the original size of the object
    private Point _size;
  2. Now create a MouseDown method. Insert this code:
        _mouseDown = true;
    _orig = Cursor.Position;
    _size = new Point(Width, Height);
  3. Create a MouseUp method and insert:
        _mouseDown = false;
  4. Next create a MouseMove method and insert
        if (_mouseDown)
    {
    //get the difference
    _diff.X = Cursor.Position.X - _orig.X;
    _diff.Y = Cursor.Position.Y - _orig.Y;

    //change the width and height,
    //relative to the old size
    Width = _size.X + _diff.X;
    Height = _size.Y + _diff.Y;

    //modify the inner object
    innerPan.Width = Width - 8;
    innerPan.Height = Height - 8;
    }
I recommend you give the background a darker colour so that you can see the difference. Also change the cursor using this.Cursor = Cursors.[whatever];

I really hope that you find this via a high-ranking google search. I hate it when websites give bad advice.

4 incoming messages (comments):

Anonymous said...

Thanks much for the advice. I was trying to get the formula right for resizing a borderless form. Gave up and came across your stuff on the thirst page of Google (;)

Things worked well after I removed the inner object methods. Now I go to figure out doublebuffer to get rid of some nasty flicker!

Anonymous said...

that is, the first page of google.

Quintin said...

Well, I'm glad it helps... I hope you get rid of the flicker. Let me know how it goes.

It seems weird that MS wouldn't make a control re-sizeable during execution. But hey, they can't solve all our problems ;P

Anonymous said...

thx :)