Click here to Skip to main content
Click here to Skip to main content

Allow the User to Resize Controls at Runtime

, 2 Oct 2007
Rate this:
Please Sign up or sign in to vote.
Enable resizing of controls on a form at runtime with this class and two lines of code.

Introduction

After searching the Web (including this site) for some simple code that would allow end users to resize controls at runtime, I finally concluded that there was not anything really effective yet really simple that I could even use as a base. I was perfectly willing to modify something to do what I wanted it to do, but most implementations were either buggy, or over-complicated, or just plain bad. I didn't find a single implementation that actually worked well.

Eventually, I decided to write my own. I did, and it was relatively simple (took about 2 hours to write), and it is very easy to use.

Background

Basically, all we are trying to do here is create something that will allow the user to resize and move controls around at runtime, similar to how we developers are able to do at design-time. This code gives you (the developer) a fairly solid baseline from which you can create any custom behavior you want. Compared to other implementations I've found, this is the simplest and most effective I've seen.

Using the Code

It basically consists of a class that can be included anywhere in your project, and then a couple of lines of code to "hook" the class to the control that you want to enable for runtime resizing.

To start with, let's just look at how you "hook" the control (in other words, how the class is used to make any control resizable at runtime):

Public Class Form1

    Dim rc As ResizeableControl

    Private Sub Form1_Load(ByVal sender As System.Object, 
    ByVal e As System.EventArgs) Handles MyBase.Load

        rc = New ResizeableControl(pbDemo)

    End Sub

End Class

That's it! Simple enough, right?

You'll want to keep the rc variable at the form level so that it doesn't drop out of scope. When the form loads, just create an instance of ResizeableControl, pass it the control that you want to be resizable (a picturebox named pbDemo in this example, but it could be any control), and assign the new instance to the form level rc variable. If you wanted multiple controls to be resizable, you might create an array or collection of ResizeableControl objects at the form level.

Now let's take a look at the class itself:

Public Class ResizeableControl

    Private WithEvents mControl As Control
    Private mMouseDown As Boolean = False
    Private mEdge As EdgeEnum = EdgeEnum.None
    Private mWidth As Integer = 4
    Private mOutlineDrawn As Boolean = False

    Private Enum EdgeEnum
        None
        Right
        Left
        Top
        Bottom
        TopLeft
    End Enum

    Public Sub New(ByVal Control As Control)
        mControl = Control
    End Sub

    Private Sub mControl_MouseDown(ByVal sender As Object, _
        ByVal e As System.Windows.Forms.MouseEventArgs) _
        Handles mControl.MouseDown

        If e.Button = Windows.Forms.MouseButtons.Left Then
            mMouseDown = True
        End If
    End Sub

    Private Sub mControl_MouseUp(ByVal sender As Object, _
        ByVal e As System.Windows.Forms.MouseEventArgs) _
        Handles mControl.MouseUp

        mMouseDown = False
    End Sub

    Private Sub mControl_MouseMove(ByVal sender As Object, _
    ByVal e As System.Windows.Forms.MouseEventArgs) _
    Handles mControl.MouseMove

        Dim c As Control = CType(sender, Control)
        Dim g As Graphics = c.CreateGraphics
        Select Case mEdge
            Case EdgeEnum.TopLeft
                g.FillRectangle(Brushes.Fuchsia, _
            0, 0, mWidth * 4, mWidth * 4)
                mOutlineDrawn = True
            Case EdgeEnum.Left
                g.FillRectangle(Brushes.Fuchsia, _
            0, 0, mWidth, c.Height)
                mOutlineDrawn = True
            Case EdgeEnum.Right
                g.FillRectangle(Brushes.Fuchsia, _
            c.Width - mWidth, 0, c.Width, c.Height)
                mOutlineDrawn = True
            Case EdgeEnum.Top
                g.FillRectangle(Brushes.Fuchsia, _
            0, 0, c.Width, mWidth)
                mOutlineDrawn = True
            Case EdgeEnum.Bottom
                g.FillRectangle(Brushes.Fuchsia, _
            0, c.Height - mWidth, c.Width, mWidth)
                mOutlineDrawn = True
            Case EdgeEnum.None
                If mOutlineDrawn Then
                    c.Refresh()
                    mOutlineDrawn = False
                End If
        End Select

        If mMouseDown And mEdge <> EdgeEnum.None Then
            c.SuspendLayout()
            Select Case mEdge
                Case EdgeEnum.TopLeft
                    c.SetBounds(c.Left + e.X, c.Top + e.Y, _
            c.Width, c.Height)
                Case EdgeEnum.Left
                    c.SetBounds(c.Left + e.X, c.Top, _
            c.Width - e.X, c.Height)
                Case EdgeEnum.Right
                    c.SetBounds(c.Left, c.Top, _
            c.Width - (c.Width - e.X), c.Height)
                Case EdgeEnum.Top
                    c.SetBounds(c.Left, c.Top + e.Y, _
            c.Width, c.Height - e.Y)
                Case EdgeEnum.Bottom
                    c.SetBounds(c.Left, c.Top, _
            c.Width, c.Height - (c.Height - e.Y))
            End Select
            c.ResumeLayout()
        Else
            Select Case True
                Case e.X <= (mWidth * 4) And _
            e.Y <= (mWidth * 4) 'top left corner
                    c.Cursor = Cursors.SizeAll
                    mEdge = EdgeEnum.TopLeft
                Case e.X <= mWidth 'left edge
                    c.Cursor = Cursors.VSplit
                    mEdge = EdgeEnum.Left
                Case e.X > c.Width - (mWidth + 1) 'right edge
                    c.Cursor = Cursors.VSplit
                    mEdge = EdgeEnum.Right
                Case e.Y <= mWidth 'top edge
                    c.Cursor = Cursors.HSplit
                    mEdge = EdgeEnum.Top
                Case e.Y > c.Height - (mWidth + 1) 'bottom edge
                    c.Cursor = Cursors.HSplit
                    mEdge = EdgeEnum.Bottom
                Case Else 'no edge
                    c.Cursor = Cursors.Default
                    mEdge = EdgeEnum.None
            End Select
        End If
    End Sub

    Private Sub mControl_MouseLeave(ByVal sender As Object, _
        ByVal e As System.EventArgs) _
        Handles mControl.MouseLeave

        Dim c As Control = CType(sender, Control)
        mEdge = EdgeEnum.None
        c.Refresh()
    End Sub

End Class

That is all there is to it. You can download the example and give it a try, or just cut and paste the code from this article.

Points of Interest

As you can see, not a whole lot of code, but enough to make it work. I would suggest you use this as a starting point, and then customize it to suit your needs.

For example, the Fuchsia borders could be replaced with sizing handles and a dashed line around the control (like the .NET forms designer). You could also add the ability to grab a corner and stretch the control vertically and horizontally at the same time (again, like the .NET forms designer).

There is really no limit to what you could do, but at least this gives you a place to start, and it works pretty good "right out of the box".

Enjoy!

History

  • 2nd October, 2007: Initial post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Jesse Chunn
Web Developer
United States United States
Jesse Chunn ran Standard I-O, a software consulting company, for 10 years before selling the company in 2005. Jesse is an experienced speaker on topics such as VB.Net, ASP.Net, web services, custom controls, and various other .Net topics.

Comments and Discussions

 
GeneralSome Updated Code [modified] PinmemberMember 1090774026-Jun-14 2:30 
SuggestionI have modified this quite heavily and made it much better...(Don't mean to be rude:D) PinprofessionalJosh-Mason113-Sep-13 19:45 
GeneralRe: I have modified this quite heavily and made it much better...(Don't mean to be rude:D) PinmemberJesse Chunn4-Sep-13 10:51 
GeneralRe: I have modified this quite heavily and made it much better...(Don't mean to be rude:D) PinprofessionalJosh-Mason115-Sep-13 6:42 
GeneralRe: I have modified this quite heavily and made it much better...(Don't mean to be rude:D) PinmemberJesse Chunn20-Apr-14 10:26 
QuestionPlease help adding drag to this great solution PinmemberDutchLeo6-Apr-13 6:09 
AnswerRe: Please help adding drag to this great solution PinprofessionalJosh-Mason114-Sep-13 9:30 
QuestionExtremely Helpful PinmemberMathGeekQ25-Feb-13 9:29 
QuestionHow to resize a veritcal scroll bar? PinmemberMember 769168111-Oct-12 10:55 
QuestionHelp to create a resizable button! PinmemberRaha2823-Jun-12 23:15 
GeneralMy vote of 5 PinmemberLanFanNinja24-Nov-11 18:35 
GeneralMy vote of 5 PinmemberArmando de la Torre18-Oct-11 9:04 
GeneralExcellent Article - Dragging Made Easy ! Pinmemberkasbaba6-Mar-10 23:36 
AnswerFinal Version With Some Enhancements by Braian87b PinmemberMember 378650823-Nov-09 7:31 
GeneralNice Job. Pinmemberbollwerkj28-May-09 7:45 
QuestionSmall problem? PinmemberPSU Steve27-Feb-09 3:11 
GeneralAwesome! I tweaked it a bit... PinmemberPSU Steve13-Feb-09 4:59 
GeneralSmall enchancement PinmemberAthmok17-Nov-08 4:26 
GeneralGood Work.. Pinmemberkalvagadda19-May-08 11:09 
GeneralQuite impressive Pinmemberketansnadar1-Jan-08 19:59 
QuestionGood code! But what about providing contol events to the nested one? PinmemberAikinX14-Oct-07 20:15 
AnswerRe: Good code! But what about providing contol events to the nested one? PinmemberJesse Chunn15-Oct-07 4:43 
QuestionWM_NCHITTEST Pinmemberanton_nix10-Oct-07 16:14 
Generalshould be an ExtenderProvider PinmemberJay R. Wren10-Oct-07 10:51 
GeneralNice solution. PinmemberRoman5448-Oct-07 20:27 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web02 | 2.8.140821.2 | Last Updated 2 Oct 2007
Article Copyright 2007 by Jesse Chunn
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid