Tuesday 22 January 2008

Refactoring Windows Forms

I have been attempting to refactor some Windows Forms classes that contain hundreds of controls and have thousands of lines of code behind. What I would like to do is to group a load of controls together and make a new UserControl that contains them. The only trouble is, there seems no easy way to do this. None of the refactoring tools seem support it, and if you were to simply try to cut and paste the controls using the Windows Forms designer you would end up losing all your event handlers and potentially messing up the relative positioning of all your controls (lots of docking and anchoring is going on).

My approach in the end was to make a complete copy of the entire class in question and delete parts from it. Then I have spent two whole days trying to reduce the compiler error count to zero (I'm down to just 19 now from 387). Even so I now have a whole bunch of event handlers that need to be hooked up and a horrible feeling that my new panel will not quite work exactly like the old one did.

So what's the point of this post? Well just to say, wouldn't it be nice if one of the .NET refactoring tool companies would implement this? Allow you to select a bunch of GUI components on a form to move to a new UserControl, expose the appropriate properties and events, and hook up the old code to access the new control. Obviously you would want to perform more refactoring after doing this, to clean up the interface to your new UserControl, but it would be an invaluable tool in managing Windows Forms projects that have got out of control.