Posted in:

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.

Want to learn more about Windows Forms? Be sure to check out my Pluralsight course Windows Forms Best Practices.

Comments

Comment by Jax

Heh, that's one of the reasons I hook events up in code as opposed to the designer.
Designer has a habit of burning you later.

Jax
Comment by Mark H

yes, unfortunately I wasn't involved in the original development of the components in question.

in fact, I gave up yesterday as the "refactoring" was turning into a "rewrite" and I couldn't afford to take the risk of breaking everything

Comment by PatrickSmacchia

Mark we're in the process of heavy Winforms refactoring too in order to get as much code as possible independent from any UI Fx to prepare the future. I know this is not exactly the topic of your post but this might be an idea https://blog.ndepend.com/wp...

PatrickSmacchia