When developing a real-world application in Windows Forms .NET, you usually have multiple menus, tool bars, ribbons, context menus, etc.
The challenge here is to provide central handlers to perform actions (e.g. an action to open a file) that came from various sources (e.g. the user clicks a menu item, or a tool bar item).
(Screenshot from my article on CodeProject about the same topic)
In the pre-.NET days there were the Microsoft Foundation Classes (MFC) that came with what they call „Command Routing„.
In MFC’s command routing the framework was responsible of correctly dispatching to the correct handler. In the handler you could specify (among other things):
- Whether the command’s visual representation (a button, a menu item, …) is displayed in enabled or disabled state.
- The action to perform when the command is being executed.
The dispatching took place automatically, depending on the current focused window.
.NET Windows Forms
Now when Windows Forms appeared, they completely lacked this command routing framework.
Therefore I developed my own minimal version that is nearly-bug-free for some projects. You can download an example project here.
Since there are more approaches by other developers to solve the lack of command routing in Windows Forms, I want to use this article to list the good ones I found:
- „Using the Command Pattern in Windows Forms clients“ – Weblog article by Jason Kemp, dated 2006.
- „How to route events in a Windows Forms application“ – Article on Code Project, dated 2005.
- „Broadcasting Events through a Control Hierarchy“ – Article on Code Project, dated 2006.
- „Zeta Producer Command Routing“ – Article of myself on Code Project, dated 2010.
- The commercial DevComponents library comes with a command routing component, although I did not yet evaluate this one.
I’m looking forward to read your resources, feel free to post them here in the comments section below.
Windows Presentation Foundation (WPF)
To be honest, I do have no practical experiences in WPF. Luckily my co-worker Dennis has a Microsoft certification on WPF.
From what I do understand, WPF does have very decent command routing. Maybe some reader can comment on whether it would be possible to extract parts of the WPF command routing and use it in Windows Forms? (Here is a German discussion about that topic)
I hope that I will soon be able to try WPF in my own projects. 🙂
(Keyword: event routing event bubbling bubble event tree hierarchy)
Ein Gedanke zu „Command Routing in Windows Forms .NET“